AppleScript: Use Dialog Return to Rename File - applescript

I'm attempting to create a Folder Action within Automator on Mac where when a new file is dropped into my specified folder, a dialog box opens asking which file I'm dropping in -- then, based on that selection, would automatically rename it to the dialog return and ideally a variable of today's date (while leaving the same extension).
Pretty new to AppleScripts but this is what I have so far which doesn't give me any errors but also doesn't do anything:
on run
set theChoice to {"Option1", "Option2", "Option3", "Option4", "Other"}
set selected to {choose from list theChoice}
if selected is "Option1" then
tell application "Finder"
set currentFile to name of (selection as alias)
set currentName to name of currentFile
set name of currentFile to "Option1" & "." & name extension of currentFile
end tell
else if selected is "Option2" then
tell application "Finder"
set currentFile to name of (selection as alias)
set currentName to name of currentFile
set name of currentFile to "Option2" & "." & name extension of currentFile
end tell
else if selected is "Option3" then
tell application "Finder"
set currentFile to name of (selection as alias)
set currentName to name of currentFile
set name of currentFile to "Option3" & "." & name extension of currentFile
end tell
else if selected is "Option4" then
tell application "Finder"
set currentFile to name of (selection as alias)
set currentName to name of currentFile
set name of currentFile to "Option4" & "." & name extension of currentFile
end tell
else
tell application "Finder"
set currentFile to name of (selection as alias)
set currentName to name of currentFile
set name of currentFile to alias & "." & name extension of currentFile
end tell
end if
end run
After figuring this part out I was also hoping to add a today's date (e.g. "_20160510") variable to the end of each filename, so if that's possible to include also that'd be great.

I've edited my quick answer. There may be other issues. I'll have to look at this a bit later. But this seems to work. You're going to have to get better at isolating smaller sections of code before putting too much together. Make sure you know what something returns first.
Look over the differences between the original code and this. You'll notice that
I added "without multiple selections"
You don't need to put choose from list in another list, so I've changed that, and gotten rid of "item 1 of item 1 of" because now selected is a simple list
I took out extra "name of"
I put in if/then to cover for cancel (which returns false)
on run
set theChoice to {"Option1", "Option2", "Option3", "Option4", "Other"}
set selected to (choose from list theChoice without multiple selections allowed)
if selected is not false then
if item 1 of selected is "Option1" then
tell application "Finder"
set currentFile to (selection as alias)
set currentName to name of currentFile
set name of currentFile to "Option1" & "." & name extension of currentFile
end tell
else if item 1 of selected is "Option2" then
tell application "Finder"
set currentFile to (selection as alias)
set currentName to name of currentFile
set name of currentFile to "Option2" & "." & name extension of currentFile
end tell
else if item 1 of selected is "Option3" then
tell application "Finder"
set currentFile to (selection as alias)
set currentName to name of currentFile
set name of currentFile to "Option3" & "." & name extension of currentFile
end tell
else if item 1 of selected is "Option4" then
tell application "Finder"
set currentFile to (selection as alias)
set currentName to name of currentFile
set name of currentFile to "Option4" & "." & name extension of currentFile
end tell
else
tell application "Finder"
set currentFile to (selection as alias)
set currentName to name of currentFile
--set name of currentFile to alias & "." & name extension of currentFile
--what is it you want to do here??
end tell
end if
end if
end run
[EDIT]
For suggestions in adding leading zeroes to date numbers, see http://www.foodoo.sunreal.com.au/info/date_info.html
it's old, but still appropriate.
Also, consider (if possible) using the do shell script command, like:
do shell script "date +\"%m-%d-%y-%H-%M-%S\""
which will return something like
"05-12-16-11-46"
( See http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/ )
As for using this stuff in Automator, it may help to see what you're doing in Automator.

This is a shorter version of the script summarizing redundant code
set theChoice to {"Option1", "Option2", "Option3", "Option4", "Other"}
set selected to {choose from list theChoice}
if theChoice is false then return
set chosen to item 1 of theChoice
tell application "Finder" to set theSelection to selection
if theSelection is {} then return
set currentFile to item 1 of theSelection
set currentDate to do shell script "date +%Y%d%m"
if chosen is "Other" then
tell application "Finder"
-- do something with "Other"
end tell
else
tell application "Finder"
set name of currentFile to chosen & "_" & currentDate & "." & name extension of currentFile
end tell
end if

Related

Renaming files randomly with AppleScript isn't working

I would like to take a directory's files and rename them by reassigning their existing filenames randomly among the same files.
For example, if a directory had the following three files (name and file size):
filenameA 100KB
filenameB 200KB
filenameC 300KB
After running the script, it might look like this:
filenameB 100KB
filenameC 200KB
filenameA 300KB
So there would be 6 permutations for three files, 24 for four files, etc….
tell application "Finder"
tell application "System Events" to set theFiles to every file of folder "/path/to/my/directory"
repeat count of theFiles times
tell application "System Events" to set theFiles to every file of folder "/path/to/my/directory"
set randint1 to random number from 1 to count of theFiles
set randint2 to random number from 1 to count of theFiles
set theName1 to name of item randint1 of theFiles
set theName2 to name of item randint2 of theFiles
set name of item randint1 of theFiles to "randomname"
set name of item randint2 of theFiles to theName1
set name of item randint1 of theFiles to theName2
end repeat
end tell
Running this code doesn't return any errors, however it doesn't work either.
I hope it's clear what the script is supposed to do.
It isn't pretty but this following AppleScript code should accomplish, what I believe you are looking to achieve.
activate
set containingFolder to (choose folder) as text
tell application "Finder"
set theFiles to files of alias containingFolder as alias list
end tell
set theNumber to 0
set numberList to {}
set randomNumbersList to {}
repeat (count of theFiles) times
set theNumber to theNumber + 1
set end of numberList to theNumber
end repeat
repeat with thisNumber in numberList
set thisNumber to some item of numberList
if thisNumber is not in randomNumbersList then
set end of randomNumbersList to thisNumber
else
repeat while randomNumbersList contains thisNumber
set thisNumber to some item of numberList
delay 0.01
end repeat
set end of randomNumbersList to thisNumber
end if
end repeat
tell application "System Events"
repeat with i from 1 to count of theFiles
set thisItem to item i of theFiles
set name of thisItem to "randomname " & ¬
(item i of randomNumbersList as text) & "." & name extension of thisItem
end repeat
end tell
After grabbing the initial files and file names, this script randomizes the file names into a separate list. It then temporarily renames each file to prevent name collisions. Finally, it cycles through each file and changes its file name to a random one and removes that name from the pool of eligible names.
tell application "Finder"
-- choose folder, list its files and file names
set baseFol to choose folder
set origFiles to files of baseFol as alias list -- list of files
set origNames to name of files of baseFol as alias list -- list of file names
-- create list of randomized names
set randNames to {}
set cc to 0
repeat count of origNames times -- pool of file names
set cc to cc + 1 -- increment counter to one above current list length
repeat until (count of randNames) is cc
set somName to some item of origNames
if randNames does not contain somName then
set end of randNames to somName -- increment list length to match counter
end if
end repeat
end repeat
-- temporarily rename files to avoid name collisions
repeat with tmpName in origFiles
set name of tmpName to "g" & space & name of tmpName
end repeat
set tmpFiles to files of baseFol as alias list -- all g-files list
-- rename each file to final name
repeat with finNames in tmpFiles
set name of finNames to (item 1 of randNames) -- use random name
set randNames to rest of randNames -- remove used name from name pool
end repeat
end tell

Is there an AppleScript I can write to remove the first instance of a character in a file name?

In the image below, I am trying to edit every file name in the cat directory so it only contains one "." For example, I need the first file name to be cat1.jpg and so forth for all of the other file names.
Do any of you all mind providing me some guidance on how I can implement an AppleScript (with Automator?) to rename all of the files in this cat directory?
Let's assume that all the files you want to rename are in a folder on your desktop named "Cat"
This following AppleScript code will remove the first instance of "." ... Leaving an empty space in its place. So, "cat.1.jpg" will be renamed to "cat 1.jpg" etc.
property theFolder : ((path to desktop) as text) & "Cat"
property originalFileName : missing value
property originalFileNameExtension : missing value
tell application "Finder" to set theFiles to (files of folder theFolder) as alias list
repeat with i from 1 to count of theFiles
set thisItem to item i of theFiles
tell application "System Events"
set fileInfo to thisItem's properties
set {originalFileName, originalFileNameExtension} to ¬
{name of fileInfo, name extension of fileInfo}
end tell
set theOffset to offset of originalFileNameExtension in originalFileName
set shortName to text 1 thru (theOffset - 2) of originalFileName
set text item delimiters to "."
set tempText to every text item of shortName
set text item delimiters to " "
set cleanedName to (tempText as text) & "." & originalFileNameExtension
tell application "System Events" to set name of thisItem to cleanedName
end repeat
This would be a full AppleScript solution to your question. But if this is only a one time event for you, mass renaming of the files through Finder, would be a quicker solution.
Answering the question in the title, once you cycle through strings in a repeat loop, to remove the first instance of a string from a string you can:
Use offset:
set s to "foo.bar.txt"
set o to offset of "." in s
set r to (text 1 thru (o - 1) of s) & (text (o + 1) thru -1 of s)
Use Applescript's Text Item Delimiters:
set AppleScript's text item delimiters to "."
set l to text items of s
set r to (item 1 of l) & (text items 2 thru -1 of l as string)
set AppleScript's text item delimiters to ""

How to append a random string to filenames using Script Editor [Mac OS]

I have a folder filled with pdf files.
filename_1.pdf
filename_2.pdf
filename_3.pdf
etc...
I am looking for a way to go from those filenames to something like :
filename_1973878763487.pdf
filename_27523765376346.pdf
filename_326537652376523.pdf
I came across the following script that changes filenames to random numbers :
tell application "Finder"
repeat with this_item in (get items of window 1)
set name of this_item to ((random number from 1000 to 9999) & "." & name extension of this_item) as string
end repeat
end tell
The script outputs something like this :
3598.pdf
7862.pdf
8365.pdf
So i need a way to append the random numbers to the original filename.
This should work for you
tell application "Finder"
repeat with thisItem in (get items of window 1)
set fileName to name of thisItem
tell current application
set theOffset to offset of "_" in fileName
end tell
set tempFileName to text 1 thru (theOffset + 1) of fileName
tell current application
set randomNumber to (random number from 1000 to 9999)
end tell
set name of thisItem to tempFileName & (randomNumber & "." & name extension of thisItem) as string
end repeat
end tell

applescript to create multiple sequentially numbered folders with a specific prefix

I would like to create an applescript that will create multiple folders with the same root name but the numbers change? or at least a repeating folder creation script until the person has enough folders. So something that makes folders like this: JOYR-15-0035-00, JOYR-15-0036-00, JOYR-15-0037-00 and so on. Is that at all possible? I am just learning this. I am normally a graphic designer but I feel like I can get a lot from applescript.
Currently I just have this basic script:
tell application "Finder"
set KDID to text returned of (display dialog "Enter the KDID ID:" default answer "JOYR-")
set loc to choose folder "Choose Parent Folder Location"
set newfoldername to {name:KDID}
set newfo to make new folder at loc with properties {name:KDID}
reveal newfo
end tell
Try this, it assumes that the KDID is just the number 15 in the example, the syntax is always JOYR-<KDID>-<consecutive number>-00 and the leading JOYR as well as the trailing double zero don't change.
The script asks for the parent folder, the KDID and the number of sequential folders. Then it checks the parent folder for the greatest existing number (the 0035 part) and creates folders starting with the greatest number plus 1 or – if no existing folders are found – with 1. The number has always four digits.
property letterPrefix : "JOYR"
property KDID : "15"
property parentFolder : missing value
set parentFolder to choose folder "Choose Parent Folder Location"
tell application "Finder"
activate
set KDID to text returned of (display dialog "Enter the KDID ID:" default answer "15")
repeat
set howManyFolders to text returned of (display dialog "Enter the Number of Folders to create:" default answer "1")
try
set howManyFolders to howManyFolders as integer
if howManyFolders < 1 then error
exit repeat
on error
display dialog "Please enter an integer value greater than 0" default answer "1"
end try
end repeat
set currentNumber to my getGreatestFolderNumber()
repeat howManyFolders times
set folderName to letterPrefix & "-" & KDID & "-" & my pad(currentNumber) & "-00"
make new folder at parentFolder with properties {name:folderName}
set currentNumber to currentNumber + 1
end repeat
open parentFolder
end tell
on getGreatestFolderNumber()
tell application "Finder"
set {ASTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "-"}
try
set folderNames to name of folders of parentFolder whose name starts with (letterPrefix & "-" & KDID & "-")
set maxNumber to 0
repeat with aName in folderNames
set curNumber to (text item 3 of aName) as integer
if curNumber > maxNumber then set maxNumber to curNumber
end repeat
set AppleScript's text item delimiters to ASTID
return maxNumber + 1
on error
set AppleScript's text item delimiters to ASTID
return 1
end try
end tell
end getGreatestFolderNumber
on pad(v)
return text -4 thru -1 of ("000" & v)
end pad

Applescript: Get filenames in folder without extension

I can get the names of all files in a folder by doing this:
tell application "Finder"
set myFiles to name of every file of somePath
end tell
How can I change the strings in myFiles so that they do not include the file extension?
I could for example get {"foo.mov", "bar.mov"}, but would like to have {"foo", "bar"}.
Current solution
Based on the accepted answer I came up with the code below. Let me know if it can be made cleaner or more efficient somehow.
-- Gets a list of filenames from the
on filenames from _folder
-- Get filenames and extensions
tell application "Finder"
set _filenames to name of every file of _folder
set _extensions to name extension of every file of _folder
end tell
-- Collect names (filename - dot and extension)
set _names to {}
repeat with n from 1 to count of _filenames
set _filename to item n of _filenames
set _extension to item n of _extensions
if _extension is not "" then
set _length to (count of _filename) - (count of _extension) - 1
set end of _names to text 1 thru _length of _filename
else
set end of _names to _filename
end if
end repeat
-- Done
return _names
end filenames
-- Example usage
return filenames from (path to desktop)
From http://www.macosxautomation.com/applescript/sbrt/index.html :
on remove_extension(this_name)
if this_name contains "." then
set this_name to ¬
(the reverse of every character of this_name) as string
set x to the offset of "." in this_name
set this_name to (text (x + 1) thru -1 of this_name)
set this_name to (the reverse of every character of this_name) as string
end if
return this_name
end remove_extension
Single line way of doing it, no Finder, no System Events. So more efficient and faster. Side effect (could be good, or bad): a file name ending with "." will have this character stripped out. Using "reverse of every character" makes it works if the name as more than one period.
set aName to text 1 thru ((aName's length) - (offset of "." in ¬
(the reverse of every character of aName) as text)) of aName
The solution as a handler to process a list of names:
on RemoveNameExt(aList)
set CleanedList to {}
repeat with aName in aList
set the end of CleanedList to text 1 thru ((aName's length) - (offset of ¬
"." in (the reverse of every character of aName) as text)) of aName
end repeat
return CleanedList
end RemoveNameExt
Here's an applescriptish method to get Finder's idea of what the stripped filename is but please note it will only work if you have NOT enabled the option in Finder's preferences to "Show all filename extensions":
set extension hidden of thisFile to true
set thisName to displayed name of thisFile
-- display dialog "hey"
set extension hidden of thisFile to false
Here's a full script that does what you wanted. I was reluctant to post it originally because I figured there was some simple one-liner which someone would offer as a solution. Hopefully this solution is not a Rube Goldberg way of doing things.
The Finder dictionary does have a name extension property so you can do something like:
tell application "Finder"
set myFiles to name extension of file 1 of (path to desktop)
end tell
So the above will get you just the extension of the first file on the user's desktop. It seems like there would be a simple function for getting the (base name - extension) but I didn't find one.
Here's the script for getting just the filenames without extension for every file in an entire directory:
set filesFound to {}
set filesFound2 to {}
set nextItem to 1
tell application "Finder"
set myFiles to name of every file of (path to desktop) --change path to whatever path you want
end tell
--loop used for populating list filesFound with all filenames found (name + extension)
repeat with i in myFiles
set end of filesFound to (item nextItem of myFiles)
set nextItem to (nextItem + 1)
end repeat
set nextItem to 1 --reset counter to 1
--loop used for pulling each filename from list filesFound and then strip the extension
--from filename and populate a new list called filesFound2
repeat with i in filesFound
set myFile2 to item nextItem of filesFound
set myFile3 to text 1 thru ((offset of "." in myFile2) - 1) of myFile2
set end of filesFound2 to myFile3
set nextItem to (nextItem + 1)
end repeat
return filesFound2
Though the above script does work if anyone knows a simpler way of doing what the OP wanted please post it cause I still get the sense that there should be a simpler way of doing it. Maybe there's a scripting addition which facilitates this as well. Anyone know?
Based on Lauri Ranta's nice solution, which works for extensions that Finder doesn't know about:
set delims to AppleScript's text item delimiters
set AppleScript's text item delimiters to "."
set myNames to {}
tell application "Finder"
set myFiles to name of every file of (path to Desktop)
repeat with myfile in myFiles
set myname to name of file myfile
if myname contains "." then set myname to (text items 1 thru -2 of myname) as text
set end of myNames to myname
end repeat
end tell
set AppleScript's text item delimiters to delims
return myNames
I don't know how to remove the extensions when you use the "every file"
syntax but if you don't mind looping (loop not shown in example) through each file then this will work:
tell application "Finder"
set myFile to name of file 1 of somePath
set myFile2 to text 1 thru ((offset of "." in myFile) - 1) of myFile
end tell
Within a tell "Finder" block this collects file names stripped of the extension in myNames:
repeat with f in myFiles
set myNames's end to ¬
(f's name as text)'s text 1 thru -(((f's name extension as text)'s length) + 2)
end repeat
For a single file I found the answer here, copied below.
set theFileName to "test.jpg"
set thePrefix to text 1 thru ((offset of "." in theFileName) - 1) of theFileName
This is a little more than you need, but it will handle more than one "." in a file name.
Assuming that a file alias is passed in to the method.
on Process(myFileAlias)
set myFile to myFileAlias as string
set AppleScript's text item delimiters to ":"
set myItemCount to the number of text items in myFile
set myFileName to the last text item of myFile
set myFilePath to text items 1 through (myItemCount - 1) of myFile
set AppleScript's text item delimiters to "."
set myItemCount to the number of text items in myFileName
set myExtension to the last text item of myFile
// This line is the key.
set myShortFilename to text items 1 through (myItemCount - 1) of myFileName as string
log (myFileName)
log (myShortFilename)
end

Resources