Applescript delete specific text and add prefix and suffix

I am very new at applescript and looking for a script to delete specific text from a files name, then add the folder name to the beginning of the name and a suffix to the name.

For example:

File name 22-M1FTV5-1_common in job folder 20-23

looking for result

2023_22-M1FTV51-1_FINAL.


I have 2 separate scripts (one to delete common text the other to rename but having trouble getting just one script).

Thank you for any help! :)

Posted on Oct 10, 2023 7:43 AM

Reply
10 replies

Oct 10, 2023 2:34 PM in response to Peter C M

The thing about replacements and concatenations is that things must be deterministic. The folder name must have that "-" separating two numbers that are to form the prefix. And the string "common" needs to be where you say it is in the filenames. The following script achieves your goal above, by selecting the folder, forming it into a prefix string, and iterating through all of the files in the folder that have "_common" in their name string. These get processed and renamed according to your goal above.


use scripting additions

set suffix to "FINAL"

set f to (choose folder)

tell application "Finder"
	-- inherently split HFS path on colons into an array
	set split to (f as text)'s words
	-- concatenate folder name components (last two items) together
	set prefix to (item -2 of split) & (item -1 of split) as text
	-- get every file in the selected folder
	set flist to (every item in folder f) as alias list
	
	if (count of flist) = 0 then return
	
	repeat with anItem in flist
		-- check if file qualifies for renaming
		if name of anItem contains "_common" then
			set nameStr to anItem's name
			-- strip "common" and replace with suffix string
			set tmp to text 1 thru (offset of "_" in nameStr) of nameStr & suffix
			-- concatenate prefix, "_" to rest of name string
			set newname to prefix & "_" & tmp
			log (newname) as text
			-- rename the file in the folder to the new name
			set name of anItem to newname
		end if
	end repeat
end tell
return


Tested on macOS Sonoma with a folder on my Desktop named 20-23. It contained the file:


22-M1FTV5-1_common.txt


and that was renamed to


2023_22-M1FTV5-1_FINAL.txt

Oct 11, 2023 8:57 AM in response to Peter C M

Although AppleScript can be coded and saved as a drag and drop solution, its reliability to detect all dropped files is inconsistent. For that reason, I have decided to use an Automator application that does work correctly when one or more files are dropped on it.


The Automator application uses just one action, Run AppleScript and the AppleScript code has changed according to your last functionality request. Now it processes all dropped files on it. If it detects a PDF document, and that PDF document contains a "_common" string, the PDF will receive the current file's parent folder as a prefix, and the common string is replaced by FINAL.


Example for a PDF on the Desktop dropped on the application:


22-M1FTV5-1_common.pdf => Desktop_22-M1FTV5-1_FINAL.pdf


Example for any other file containing "_common":


22-M1FTV5-1_common.txt => 22-M1FTV5-1.txt


Tested on macOS Sonoma 14.0.


  1. Launch Automator from your Applications folder.
    1. New Document
    2. Application
    3. Choose
  2. Enter Run AppleScript in the search field.
    1. Drag and drop the Run AppleScript action to the right onto the larger workflow window
    2. Select all text in it and hit backspace to remove its content.
    3. Copy and paste the following AppleScript below into that Run AppleScript action, and click the hammer icon to compile it. The text will change from purple to multiple colors to signify success.
  3. Save the Automator application to your Desktop with some meaningful name (.e.g. Fix_DocumentNames).
  4. Quit Automator


Code to copy/paste into the Run AppleScript action:


(*
	Drag and drop files onto this application.
	PDFs will be renamed to foldername_filename_FINAL.pdf
	Other files will have no prefix and any occurrence of "_common"
	in the filename will be removed
 *)

use scripting additions

property suffix : "FINAL"

on run {input, parameters}
	
	tell application "Finder"
		
		repeat with anItem in input
			
			set nameStr to anItem's name
			set nameExt to "." & anItem's name extension
			-- no file extension because - 1 removes "." and extension
			set baseName to text 1 thru ((offset of "." in nameStr) - 1) of nameStr
			ignoring case
				if baseName contains "_common" and (name extension of anItem = "pdf") = true then
					-- PDF only
					set prefix to (container of anItem as text)'s last word
					set newName to prefix & "_" & text 1 thru (offset of "_" in baseName) of baseName & suffix & nameExt
				else
					-- other file types where we strip out any "_common" presence
					set newName to text 1 thru ¬
						((offset of "_" in baseName) - 1) of baseName & nameExt
				end if
			end ignoring
			log (newName) as text
			set name of anItem to newName
		end repeat
		
	end tell
	return newName
end run


Now that you have an Automator application on your Desktop, you can drag and drop one or more files onto it and it will process them. It is not configured for you to drop folders on it.


The first time you run this, it will throw a dialog asking to control Finder. Click OK (that is important). My name for the Automator application that I tested was Fix_Filenames.



Here is what the Automator appliication contents should look like when you save it.


Oct 11, 2023 7:07 AM in response to Peter C M

I am trying to modify this script to be file based instead of a folder. I want to rename just the PDF file in the folder to be the folder name_current name_Final. Not all files have the "_common" text but if it does I need to strip it out. Currently the script doesn't work if that _common text is not there. I would also like this to be an application that I can just drop the file on and run. Sorry I should have been more clear with all variable that I need. Thank you again for any help!

Oct 11, 2023 1:21 PM in response to Peter C M

Good.


It is best to get the functional AppleScript code working in Script Editor before placing it in a Run AppleScript action. Sometimes the code in the Script Editor works and the same code will misbehave in the Run AppleScript action because they use two different AppleScript run time libraries.


Further reading:


Automator User Guide for Mac - Apple Support


macOSXAutomation (older content)


Note, that Apple is transitioning from Automator to Shortcuts beginning with macOS Monterey and you should be strategically learning Shortcuts which has a different implementation than Automator. The Run AppleScript action when used in Shortcuts will drive you crazy if you attempt to interactively enter code in it.


See this link for additional Shortcuts information.



Oct 11, 2023 4:55 AM in response to Peter C M

I have made some changes to the AppleScript with comments. Now it uses the selected folder name (without '-') and automatically handles different file extensions.


use scripting additions

set suffix to "FINAL"

set f to (choose folder)

tell application "Finder"
	-- inherently split HFS path on colons into an array
	set split to (f as text)'s words
	-- get the folder name from the last list item
	set prefix to (last item of split) as text
	-- get every file in the selected folder
	set flist to (every item in folder f) as alias list
	
	if (count of flist) = 0 then return
	
	repeat with anItem in flist
		if name of anItem contains "_common" then
			set nameStr to anItem's name
			set nameExt to "." & anItem's name extension
			-- no file extension because - 1 removes "."
			set baseName to text 1 thru ((offset of "." in nameStr) - 1) of nameStr
			-- construct new filename with prefix, new basename with replacement
			-- suffix and extension
			set newName to prefix & "_" & text 1 thru ¬
				(offset of "_" in baseName) of baseName & suffix & nameExt
			set name of anItem to newName
		end if
	end repeat
end tell
return


This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Applescript delete specific text and add prefix and suffix

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.