AppleScript to Rename File Names
Can anybody help me with the following issue. I'd like an AppleScript that will rename files like these by removing the leading numbers and underscore.
So file names like these:
5111632_The Secret_ Dare to Dream.mp4 5099299_Invasion of the Body Snatchers 1.mp4 5099287_Basic Instinct.mp4 5099283_Before I Go to Sleep.mp4
would turn into:
The Secret_ Dare to Dream.mp4 Invasion of the Body Snatchers 1.mp4 Basic Instinct.mp4 Before I Go to Sleep.mp4
I'm going to run it in one folder using Hazel.
Solution 1:
The Applescript-native way to rename files is:
tell application "Finder"
set theFile to (choose file)
set name of theFile to "Yay"
end tell
If you wanted to rename every file in a folder, I'd put the files into a list and use a Repeat
block on each one:
tell application "Finder"
set theFolder to (choose folder)
set folderContents to every item of theFolder
repeat with theFile in folderContents
set name of theFile to "Yay"
end repeat
end tell
(This code won't actually run as-is because you can't have two files named "Yay", but the first does get renamed, and you get the idea.)
This is closer to what you want to do, but we're not quite there—you want to get the current file's name, make some changes to it, and save the new name.
There's a subroutine I found years ago somewhere (I can't seem to find the source now) which will get everything to the right of a certain character, such as an underscore. This makes it easy to do exactly what you want. The full, final code is:
tell application "Finder"
set theFolder to (choose folder)
set folderContents to every item of theFolder
repeat with theFile in folderContents
set oldName to name of theFile
set newName to my rightString(oldName, "_")
set name of theFile to newName
end repeat
end tell
on rightString(str, del)
local str, del, oldTIDs
set oldTIDs to AppleScript's text item delimiters
try
set str to str as string
if str does not contain del then return str
set AppleScript's text item delimiters to del
set str to str's text items 2 thru -1 as string
set AppleScript's text item delimiters to oldTIDs
return str
on error eMsg number eNum
set AppleScript's text item delimiters to oldTIDs
error "Can't rightString: " & eMsg number eNum
end try
end rightString