Troubleshooting AppleScript to Automate File Renaming in Finder

Hello

I am currently working on an AppleScript to automate the process of renaming multiple files in Finder; but I’m running into an issue where the script doesn’t seem to apply the intended renaming pattern across all selected files. :slightly_smiling_face:

The script works for a single file; but when multiple files are selected, it only renames the first one and stops without affecting the others. I would appreciate guidance on how to loop through all selected files and ensure that the renaming process applies to all of them. :innocent:

I’m using the following AppleScript to rename files:

tell application “Finder”
set selectedFiles to selection
repeat with aFile in selectedFiles
set theName to name of aFile
set name of aFile to “NewName_” & theName
end repeat
end tell

The script works well when renaming a single file; but when selecting multiple files, only the first file gets renamed. Could this be related to how the script handles the selection? :thinking: I’m not sure if I need to adjust the selection handling or the way the script interacts with the Finder to loop through all files correctly. Checked macos - Creating a batch file-renaming script for use in OSX Automator - Stack Overflow and Okta administrator documentation guide for reference .

Any advice would be much appreciated!

Thank you ! :slightly_smiling_face:

Hi @boxid. Welcome to MacScripter.

Your script works perfectly well for me with multiple files and I can’t see any reason why it shouldn’t. It might error out if a new name it’s trying to give already belongs to another item in the same folder. You can trap for this as follows. (The code assumes that the alternative name entered is viable!)

tell application "Finder"
	set selectedFiles to selection
	repeat with aFile in selectedFiles
		set theName to name of aFile
		set newName to "NewName_" & theName
		try
			set name of aFile to newName
		on error number -48
			set theContainer to container of aFile
			set {text returned:newName, button returned:bttn} to (display dialog "An item called \"" & newName & "\" already exists in folder \"" & theContainer & "\". Please enter another name…" default answer theName buttons {"Cancel", "Skip", "OK"} default button "OK")
			if (bttn = "OK") then set name of aFile to newName
		end try
	end repeat
end tell

By the way, the way to have AppleScript code appear on MacScripter in a box with an “Open in Script Editor” button as above is to post it with three backticks on separate lines above and below as tags. (See Markdown Reference.) That is:

```
AppleScript code
```