AppleScript to rename files revisited

A couple years back I blogged a script that would take a file and append the name of the enclosing folder to the beginning of the file name. For example, a file called “Testfile.txt” inside a folder called “Folderstuff” would be renamed to “Folderstuff Testfile.txt.”

A reader recently stumbled across that script and asked:

That script is exactly what I’ve been looking for, with one exception:

When saved as an application I can’t drag and drop multiple files onto it. In fact, it doesn’t seem to be able to handle multiple files at all, I just get errors.

I’ve done a bunch of searching on how to deal with multiple files but I just cant seem to make it work.

Here are some updated versions of the original script. This first one is meant to be run directly out of Script Editor on whatever files you have selected in the Finder.


tell application "Finder"
set theFiles to selection
set theCount to number of items in theFiles
repeat with i from 1 to theCount
set theFile to (item i of theFiles as text)
set TheName to name of (theFile as alias)
set thePath to POSIX path of (theFile as alias)
set parentFolderPath to text 1 thru ((offset of TheName in thePath) - 2) of
thePath
set AppleScript's text item delimiters to "/"
set parentFolder to (item -1 of text items of parentFolderPath) as string
set NewName to (parentFolder & " " & TheName)
set name of file theFile to NewName
end repeat
end tell

And this version is meant to be saved as an AppleScript applet. Drop some files (not a folder on it) and it’ll run with it.


on open theFiles
set theCount to number of items in theFiles
repeat with i from 1 to theCount
tell application "Finder"
set theFile to (item i of theFiles as text)
set TheName to name of (theFile as alias)
set thePath to POSIX path of (theFile as alias)
set parentFolderPath to text 1 thru ((offset of TheName in thePath) - 2)
of thePath
set AppleScript's text item delimiters to "/"
set parentFolder to (item -1 of text items of parentFolderPath) as string
set NewName to (parentFolder & " " & TheName)
set name of file theFile to NewName
end tell
end repeat
end open

UPDATE 2008-06-13: Reader Andrew pointed out that the script only grabs the title of the front window and won’t work if you’re in list view and have a expansion triangle open. I’ve updated the scripts to account for that.

4 thoughts on “AppleScript to rename files revisited”

  1. I’m having a hard time finding a script that will rename a series of files in sub folders with the file being appended with the name of the enclosing folder and output to a new folder. Can this be modified to handle that?

Leave a Reply

Your email address will not be published. Required fields are marked *