Skip to content

Instantly share code, notes, and snippets.

@oliveratgithub
Last active March 2, 2024 17:05
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save oliveratgithub/b9030365c9ae483984ea to your computer and use it in GitHub Desktop.
Save oliveratgithub/b9030365c9ae483984ea to your computer and use it in GitHub Desktop.
Simple AppleScript to easily batch rename multiple files sequentially. GUI asks user to select files and input a name before renaming.
-- This code comes from https://gist.github.com/oliveratgithub/
-- Open in AppleScript Editor and save as Application
-- ------------------------------------------------------------
--this is required to break the filename into pieces (separate name and extension)
set text item delimiters to "."
tell application "Finder"
set all_files to every item of (choose file with prompt "Choose the Files you'd like to rename:" with multiple selections allowed) as list
display dialog "New file name:" default answer ""
set new_name to text returned of result
--now we start looping through all selected files. 'index' is our counter that we initially set to 1 and then count up with every file.
--the 'index' number is of course required for the sequential renaming of our files!
repeat with index from 1 to the count of all_files
--using our index, we select the appropriate file from our list
set this_file to item index of all_files
set {itemName, itemExtension} to {name, name extension} of this_file
--if the index number is lower than 10, we will add a preceding "0" for a proper filename sorting later
if index is less than 10 then
set index_prefix to "0"
else
set index_prefix to ""
end if
--
--lets check if the current file from our list (based on index-number) has even any file-extension
if itemExtension is "" then
-- "" means there is no file-extension present.
set file_extension to ""
else
--yup, we are currently processing a file that has a file-extension
--we have to re-add the original file-extension after changing the name of the file!
set file_extension to "." & itemExtension
end if
--let's rename our file, add the sequential number from 'index' and add the file-extension to it
set the name of this_file to new_name & index_prefix & index & file_extension as string
end repeat
--congratulations for successfully accomplishing the batch renaming task :)
display alert "All done! Renamed " & index & " files with '" & new_name & "' for you. Have a great day! :)"
end tell
-- This code comes from https://gist.github.com/oliveratgithub/
-- Open in AppleScript Editor and save as Application
-- ------------------------------------------------------------
--this is required to break the filename into pieces (separate name and extension)
set text item delimiters to "."
-- Let the App receive drag'n'dropped files
on open theDroppedItems
-- build the file list based on the dropped files
set all_files to every item of theDroppedItems as list
tell application "Finder"
display dialog "New file name:" default answer ""
set new_name to text returned of result
--now we start looping through all selected files. 'index' is our counter that we initially set to 1 and then count up with every file.
--the 'index' number is of course required for the sequential renaming of our files!
repeat with index from 1 to the count of all_files
--using our index, we select the appropriate file from our list
set this_file to item index of all_files
set {itemName, itemExtension} to {name, name extension} of this_file
--if the index number is lower than 10, we will add a preceding "0" for a proper filename sorting later
if index is less than 10 then
set index_prefix to "0"
else
set index_prefix to ""
end if
--
--lets check if the current file from our list (based on index-number) has even any file-extension
if itemExtension is "" then
-- "" means there is no file-extension present.
set file_extension to ""
else
--yup, we are currently processing a file that has a file-extension
--we have to re-add the original file-extension after changing the name of the file!
set file_extension to "." & itemExtension
end if
--let's rename our file, add the sequential number from 'index' and add the file-extension to it
set the name of this_file to new_name & index_prefix & index & file_extension as string
end repeat
--congratulations for successfully accomplishing the batch renaming task :)
display alert "All done! Renamed " & index & " files with '" & new_name & "' for you. Have a great day! :)"
end tell
end open
@oliveratgithub
Copy link
Author

@vegaomar yes, this is possible by enhancing the AppleScript as follows:

  1. add the following code to the very bottom of the script (after end tell)
on replace_text(search_string, replacement_string, this_text)
	set prevTIDs to AppleScript's text item delimiters
	set AppleScript's text item delimiters to the search_string
	set the item_list to every text item of this_text
	set AppleScript's text item delimiters to the replacement_string
	set this_text to the item_list as string
	set AppleScript's text item delimiters to prevTIDs
	return this_text
end replace_text
  1. then change line #9 as shown in the following before & after
  • before:
set new_name to text returned of result
  • after:
set new_name to my replace_text(" ", "-", text returned of result)

@Lokissimo
Copy link

Oliver!

Thank you so much for this script... It is really helping me understand how scripting works.

I am trying to modify this for my specific task without avail. I would like to drop a folder on the droplet and have it name
all of the files within it sequentially as "Name of Folder" + "_" + number. So far, the following gets me the foldername:

on open theDroppedItems

tell application "Finder"
	
	set Foldername to (name of (info for theDroppedItems))
	display dialog Foldername as string
	set new_name to Foldername & "_"

But when I try to access the files in the folder using:

set all_files to (every file of Foldername as list)

I get an error! What am I doing wrong?

Thanks,

Matt

@oliveratgithub
Copy link
Author

@Lokissimo thanks for the feedback :)

What you want to do requires some more enhancements to the Drag-n-Drop script:

  1. First question is: do you want it to allow (multiple) Folders but ALSO Files to be drag'n'dropped? => makes it even more complicated ;)
  2. When you drag a folder onto the Script-Application, you have to go "inside" the dropped folder(s) in order to process only the files WITHIN => your code snippet renames only the Folder itself

You can find a pretty good example code here:
https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/ProcessDroppedFilesandFolders.html#//apple_ref/doc/uid/TP40016239-CH53-SW10

If I find the time, i might enhance the script to allow drag'n'dropping of Files & Folders alike. At a first try, I didn't get it to work properly.

Copy link

ghost commented Jul 7, 2019

Hi! Thanks for posting this script, its pretty much what I looked for, but I have trouble understanding what line 15+16 in your code do and what they are good for. All I know is that my version doesn't work unless I have them in there :D

These are the lines I'm talking about:

	set file_name_count to text items of (get name of this_file)
	set {itemName, itemExtension} to {name, name extension} of this_file

If you could give me some pointers, it would be very appreciated!

Thanks,
Anton

@oliveratgithub
Copy link
Author

Hi @antonkvm, thanks for your feedback - glad it is helpful :)

set file_name_count to text items of (get name of this_file)

This counts the individual parts of a files' name (e.g. filename = 1, extension = +1) and saves this number for the current file which is being processed into the variable "file_name_count". HOWEVER, this line is actually deprecated since the last script revision and should be removed (I'll do this right away). See the Revision history for how it used to be used for checking if the file has an extension – or not: Batch File Rename.scpt » Revisions

set {itemName, itemExtension} to {name, name extension} of this_file

This creates an array containing the original files 'name' and 'extension' parts and is needed to re-add the same file extension after renaming, see line #31

--we have to re-add the original file-extension after changing the name of the file!
set file_extension to "." & itemExtension

Cheers,
Oliver

Copy link

ghost commented Jul 10, 2019

Hi @oliveratgithub, thanks for the reply! I now managed to get my code to work as intended, with the help of your explanation above =)

I've noticed though that the variable "itemName" doesn't get used after it's declared together with "itemExtension" in the array, so couldn't

set {itemName, itemExtension} to {name, name extension} of this_file

be condensed to

set itemExtension to name extension of this_file

?

Again, thanks for helping me out and have a great day!

Cheers,
Anton

@oliveratgithub
Copy link
Author

@antonkvm that's correct and your change would be a viable alternative.

I decided to keep the declaration of itemName in the code, because someone who modifies the script / takes the script as a basis, may be glad to know it's there. E.g. you could write a log / message showing exactly which (old) itemName was renamed into which (new) new_name :)

Copy link

ghost commented Jul 10, 2019

@oliveratgithub true, that makes sense, that could be helpful!

@Alexollon
Copy link

Alexollon commented Dec 31, 2019

Hi guys,

I would need an Apple script that renames all files in a folder (including folders) from

originalfilename -->
YYYYMMDD_FOLDERNAME_originalfilename

where YYYYMMDD is the creation date of the file.

It should run in all subfolders automatically starting from top hierarchy down. Also Folders should be renamed with that logic.

2 Examples:
/2001 Fotos/2001 Xmas/foto1.jpg --> /2001 Fotos/2001 Fotos_2001 Xmas/2001 Fotos_2001 Xmas_foto1.jpg
/2001 Fotos/2001 Xmas/Originals/foto1.jpg --> /2001 Fotos/2001 Fotos_2001 Xmas/2001 Fotos_2001 Xmas_Originals/2001 Fotos_2001 Xmas_Originals_foto1.jpg

Would be really great to help me out!!!!

Thx guys and happy new year!
Alex

@oliveratgithub
Copy link
Author

@Alexollon I‘m afraid you‘ll need to put something like that together yourself, as it‘s a very specific scenario and needs more logic (parsing hierarchy, reading file creation time, concert such, rename files by folder, etc.).

Maybe for this case you may want to look what you could achieve using Automator.app and it‘s built in UI commands for file and folder manipulation?

@Jimmbo
Copy link

Jimmbo commented Jan 22, 2020

Since the script requires files to be selected, why does it ask us to select files in an open/save dialog?

@oliveratgithub
Copy link
Author

oliveratgithub commented Jan 22, 2020

@Jimmbo Update: I checked again and - yes - it does ask for files of course, when running the script without drag‘n‘dropping files onto it (2nd solution), because how would it otherwise know which files you want to rename?

But probably I still don’t fully understand your question @Jimmbo - can you elaborate what‘s wrong or confusing about the „Choose file…“-dialogue?

@Jimmbo
Copy link

Jimmbo commented Jan 22, 2020

Screen Shot 2020-01-22 at 11 35 04 AM

@Jimmbo
Copy link

Jimmbo commented Jan 23, 2020

If you select files, launch script, then need to navigate open/save dialog to select files, that seems a tad redundant to me. I'd expect it to just rename the files I've chosen.

@oliveratgithub
Copy link
Author

@Jimmbo ah I understand. For this use case I‘d recommend using the 2nd script and save it as an application. Then you can simply drag‘n‘drop your files onto the Script application to start renaming exactly these files.

@Jimmbo
Copy link

Jimmbo commented Jan 24, 2020

Ok, thanks. So if I understand correctly, in order to suit the script's need to check twice which files it will process, I need to slow my workflow in one of two ways:

  1. Choose files, run script, navigate open/save dialog to find and re-select files, or

  2. Choose files, reveal the script-app's icon in Finder, select files, and drag them over.

@oliveratgithub
Copy link
Author

@Jimmbo OR you ONCE save the Script Drag-n-Drop Files Batch Rename.scpt from within Script Editor as File Format "Application", then drag newly created Application's icon to your Dock.
Now you have it accessible basically all the time to drag'n'drop files onto it from everywhere in Finder. It will ask for what new name to give them still, of course – if you don't need that part of the script, remove it / hard code any custom name you always want to use or modify it to just add continuous numbering without changing the name at all.

Otherwise you use the new right-click > "Rename X items…"-function in Finder directly or use a tool like A Better Finder Rename, if that fits better into your workflow.

@Jimmbo
Copy link

Jimmbo commented Jan 24, 2020

Thanks Oliver. I actually own several renaming apps, but was looking for a script I could use within a larger script to streamline my workflow.

@AtomicNess123
Copy link

I'm looking to actually set an automator to prepend a text to file names. I have been looking for days unsuccessfully. I have managed to create a service that takes file names, creates a variable with such, and renames by prepending, but it won't work. Any help welcome!

@oliveratgithub
Copy link
Author

@Gahamelas you could modify the Apple Script from this Gist to work with a selected file within an Automator action, instead of a user dialogue to choose files. Automator is capable of running Apple Scripts within an automation step.

@AtomicNess123
Copy link

@Gahamelas you could modify the Apple Script from this Gist to work with a selected file within an Automator action, instead of a user dialogue to choose files. Automator is capable of running Apple Scripts within an automation step.

Thanks. What I want to accomplish is to select several files in Finder and then run the Automator action that will prompt me to write a name to prepend to those files. Will this do that?

@oliveratgithub
Copy link
Author

oliveratgithub commented Dec 13, 2020

What I want to accomplish is to select several files in Finder and then run the Automator action that will prompt me to write a name to prepend to those files. Will this do that?
@Gahamelas No, the Apple Script here won't do this - unless you'd adjust it.

HOWEVER, try this «Quick Action» in Automator 😉

Automator Quick Action - Prefix selected Finder items with User Input

Cheers

@Jimmbo
Copy link

Jimmbo commented Dec 13, 2020

Not to distract you from coming up with a Drafts solution, but this renaming program does that plus much more. It's awesome.

@oliveratgithub
Copy link
Author

👍 you can do it within Finder itself, to be honest… Right click files > Rename… > Add Text & Prepend. Done

@AtomicNess123
Copy link

What I want to accomplish is to select several files in Finder and then run the Automator action that will prompt me to write a name to prepend to those files. Will this do that?
@Gahamelas No, the Apple Script here won't do this - unless you'd adjust it.

HOWEVER, try this «Quick Action» in Automator 😉

Automator Quick Action - Prefix selected Finder items with User Input

Cheers

This works like a charm! I had similar workflow but I was missing some bits here and there +1: Thank you so much!

@AtomicNess123
Copy link

👍 you can do it within Finder itself, to be honest… Right click files > Rename… > Add Text & Prepend. Done

Yes, the point of the workflow is to now have to click so many times.

@PetrKGitHub
Copy link

PetrKGitHub commented Jan 19, 2021

Hi Oliver. is there any way to make the script to run once a day, go to selected folders and to rename the files in those folders to contain a specific string at the very beginning of the file name UNLESS they already contain such string? Imagine I have a folder named X007-007 and throughout the day I would save several files in the folder, at the end of the day I need all files to start with X007-007-a_v1 (where A would) be the number of the file in the folder (v1 is just for a version 1). the next day I need the script to ignore those files with the prefix (to avoid X007-007-a_v1X007-007-a_v1X.....) and just rename the files that are new....(I have several hundreds folders like this, inluding several thousands files, every day adding some 20 new files....and such script would make me 1. happy, 2. organised). In case of a new folder, I would just add one (I hope) line in the code...THANK YOU SUPER BIG TIMES

something like --- rename all files (except for those which are already renamed) in folder X007-007 to X007-007-00A_v1-original name of the file.docx

with in the end the files would be

X007-007-001_v1-opening.docx
X007-007-002_v1-randomfile.doc
X007-007-003_v1-anotherrandomfile.pdf
X007-007-004_v1-original picture.png

and if I add a new file - document.doc, in the evening once I run the script it should be renamed to

X007-007-005_v1-document.doc

(however if I duplicate a randomfile.doc and save it to X007-007-002_v2-randomfile.doc such document should not be renamed....)

@oliveratgithub
Copy link
Author

Hi Oliver. is there any way to make the script to run once a day, go to selected folders and to rename the files in those folders to contain a specific string at the very beginning of the file name UNLESS they already contain such string?

Hey @PetrKGitHub
Sure something like this would be possible, but it incorporates some additional logics, starting already with a scheduler mechanism. I think you could put something together with "crontab" (if you're technically skilled) or a macOS app giving you a UI to control repeating jobs. The rest needs either a reworked Apple Script or at least 1 additional / preceeding Script.

Overall however, it's not a simple solution and has many "moving pieces" that I can cover here :)

@laneharding
Copy link

Hi Oliver,

Thank you for the code! I love how easy it is to use. I know it would take some extra manipulation, but is there a way to have it reference a document with a list of names to use instead of using one word and putting a number at the end? Thank you in advance for your help.

@oliveratgithub
Copy link
Author

I know it would take some extra manipulation, but is there a way to have it reference a document with a list of names to use instead of using one word and putting a number at the end?

@laneharding Sure that’s possible, it requires some rework with additional code though. Here‘s a good discussion about just getting every line of a text file (.txt) into a dynamic list within the script: https://stackoverflow.com/a/48967981/5750030

The question is, if this text file will always be read from the same location, or you‘d choose it manually when the script runs? Also consider error handling when the file happens to be empty. Or what if the number of names in the text file don’t add up to the number of selected files to be renamed?

Assuming you manage to add code to read the lines from text file into a list within the script, definitely you‘d have to disable/remove lines 8 and 17-21. Then adding a repeat, looping through modifying line 9 (set new_name) to take the first name from the text file list, but making sure the next file would take also the 2nd name from the list, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment