AppleScript to rename files

Another AppleScript problem that was vexing me this morning. Again, you would think that this would be easy… I wanted to rename a file to append the name of the enclosing folder onto it.

For example, the file “Testfile.txt” inside a folder called “Folderstuff” would be renamed to “Folderstuff Testfile.txt.” Here’s the (drawn out) AppleScript code:

(*
Renames the selected file to append the enclosing folder name to the front.
*)
tell application "Finder"
activate
set theFile to selection as text
set TheName to name of (theFile as alias)
set SourceFolder to name of (folder of the front window as alias)
set NewName to (SourceFolder & " " & TheName)
set name of file theFile to NewName
end tell

I know it’s faster to do this with a shell script, but I want to keep it in AS for now.

3 thoughts on “AppleScript to rename files”

  1. i just started applescripting today…and with the help of your small script i was able to write a script that automatically changes the extensions of a certain filetype in a arbitrary directory to another filetype. Of course i had to look at several sources to do it, but your rename command was the core feature where everything started. THANK YOU for your effort.

Leave a Reply

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