You can make a difference in the Apple Support Community!

When you sign up with your Apple Account, you can provide valuable feedback to other community members by upvoting helpful replies and User Tips.

Automator: change files names and replace XXX

Hello,


I have created an automation that renames a large number of files. Changing the file name structure from a string of 20 numbers to 'CFC_CAMA_0001' using the 'Rename Finder Items: Make Sequential' action.


'CFC_CAMA_' is the new file name and the '0001' is the start of a 4 digit sequence. The next clip file will end in 0002, 0003 and so on.


This works fine but I wonder if I could add an customer reference number after the CFC so that the file name could read CFC5630_CAMA_0001, CFC5630_CAMA_0002, CFC5630_CAMA_0003 ...


If the template for the new name is 'CFCXXXX_CAMA', could a dialogue box pop up and ask what I want the XXXX to change to?


If so, how do I do this?


Thanks!

Posted on Oct 19, 2024 8:02 AM

Reply
10 replies

Oct 20, 2024 7:25 AM in response to tprloveridge

I decided to add some elaborate tests in the Run Shell Script phase of the revised workflow. Here is what it does:


  1. I have incorporated the customer reference number Finder prompt in the Run Shell Script action.
    1. Will only accept 4-digit numbers and will continue to prompt until this condition is met.
  2. Uses an array containing the CAMA, CAMB, and CAMC folder names
    1. If one just clicks the Choose button without explicit folder selection, or a first folder name that is not in that array, the script throws an error dialog and quits.
  3. One can select any or all of the CAMA, CAMB, or CAMC folders and those selected will be processed.
    1. The array of these folder names may need to be changed if different named folders are expected.
    2. I have added a validation so that if one attempts to process a folder more than once, it will check if the filenames in that folder have been processed and if not it renames them.
      1. There is no logic to rename added files after initial folder processing and resume the numeric suffix sequence.
  4. The Run Shell Script uses Zsh and its Pass input selector is set to as arguments so the selected folders are passed into the action on its virtual command line which uses the "${@}" to represent the array of those folder paths.
  5. When processing is complete, the Run Shell Script will use AppleScript to throw a dialog to that effect.


The Automator actions used in order are:

  • Files & Folders Library: Ask for Finder Items
  • Utilities Library: Run Shell Script


When you set the Run Shell Script action to Shell: /bin/zsh and Pass input: as arguments, the contents of the empty action will change to show a simple for loop. Select and remove that as you will want to paste the following code instead:


: <<"COMMENT"
Prompt the user for the 4-digit customer reference number using an AppleScript function. Then check if between 1 and 3 folders were
selected from the preceding Ask for Finder Items action. Fail if user cancels, or more than 3 are selected.

The folder names are on the arguments list ($@) provided in the first for loop, and we process each file in that folder, incrementing
its zero-padded generation number with each file. We then rename the existing file to the CFCXXXX_FOLDERNAME_nnnn.ext.

The Zsh shell's modifiers (e.g. h:r:t:e) are documented in the zshexpn man page, or in the Terminal by running the following command sequence to list just the modifier section:

mandoc -Tutf8 -man $(man -w zshexpn) | col -b | awk '/^[ \t]+Modifier/,/^PROCESS SUBSTITUTION/ {print}' | more

Tested: macOS Sequoia v15.0.1, Zsh 5.9
VikingOSX, 2024-10-20, Apple Support Communities, No warranties expressed or implied.
COMMENT

# initialize a 4-digit, zero-padded generation counter (e.g. 0001)
typeset -Z4 gen=1
typeset -a allowed_folders=( CAMA CAMB CAMC )

# prompt for customer reference number
function cust_prompt () {
    /usr/bin/osascript <<AS
    use scripting additions

    -- continue repeat loop until 4-digit number string is entered.
    repeat
        set ans to text returned of (display dialog "Enter 4-digit string of customer number: " default answer "")
        try
            set foo to ans as number
            if ((count of ans) = 4) then exit repeat
        end try
    end repeat
    
    return ans
AS
}

function fatal_error () {
	/usr/bin/osascript <<AS
	use scripting additions
	display dialog "${1}" with title "Automator Processing Error"
	return
AS
}


# Check if the first folder is one of the approved folders or if the user just pressed choose
# for instance, avoid changing every file on the Desktop.
(( ${allowed_folders[(Ie)${1:a:t}]} )) || { $(fatal_error "Not one of the approved folders."); exit 0}
[[ $# -ge 1 && $# -le 3 ]] || { $(fatal_error "Must pick between 1 and 3 folders for input… quitting."); exit 0}

# set customer reference number from its prompt
CUSTREF="$(cust_prompt)"

# process folders in order of Finder selection
for f in "${@}";
do
	# process files in each folder
	for g in ${f}/*(.N);
	do
	# rename files in folder to new format while borrowing ${f:r:t} the folder name string
	# and add on the current file extension ${g:e}.
	# if renamed file exists then skip file
	[[ -f "${g:h:r}/CFC${CUSTREF}_${f:r:t}_${gen}.${g:e}" ]] && continue
	/bin/mv "${g}" "${g:h:r}/CFC${CUSTREF}_${f:r:t}_${gen}.${g:e}"
	(( gen++ ))
	done
	# reset generation counter for next folder
	gen=1
done

/usr/bin/osascript -e 'display dialog "Processing complete." with title "Automator Completion Status"'
exit 0


The entire Automator application workflow looks like this:


Oct 19, 2024 3:03 PM in response to tprloveridge

The short answer is yes, one can create an Automator workflow to process three selected folders from an Automator Ask for Finder Items action but it will require a rewrite of the current solution as Automator is essentially a waterfall process where data flows from one action to another. It has no control flow to loop through a series of actions in a repetitive manner.


The current Get Folder Contents and Rename Finder Items actions would be replaced by a Run Shell Script action that does all of the folder and filename processing. It will take some time to write and test. The order of the folder selections in the Ask for Finder Items action will determine the folder processing order in the script.


Questions:

  1. Will the XXX customer reference number be the same for the files in each of CAMA, CAMB, and CAMC folders from a single dialog prompt, or do you expect to be prompted to enter a different reference number for each folder before it is processed?
  2. Do the selected folders contain the CAMA, CAMB, or CAMC strings in the folder names, so one could extract these during the processing for filename construction?
  3. Flat input folders or do they have a sub-folder hierarchy to process?



Oct 19, 2024 10:04 AM in response to tprloveridge

At the beginning of your Automator workflow, insert Text Library : Ask for Text followed by Library Utility : Set Value of Variable.



Note that the custRef variable is stored at the bottom of the Automator workflow and you will eventually drag and drop that into the new name field of the Rename Finder Items: Make Sequential action and then append _CAMA after it.


The whole workflow looks like this:



That menacing CFC${....}_CAMA_0001.xxx would be replaced with the value you chose for custRef in the Ask for Text action. Be careful to not type a return after the xxxx entry in that action.


Before filenames (just 20 character test files):



After filenames:




Oct 19, 2024 5:08 PM in response to tprloveridge

Thanks for the information. You can double-click the IMPORT folder and then pressing the ⌘-key, select the CAMA, CAMB, and CAMC folders which are provided in addition to the value from the customer reference number prompt. I have a working script that instead of your IMPORT folder has a TEST parent folder.


BEFORE



AFTER



Is the result you seek from a single Automator application?

Oct 19, 2024 11:51 AM in response to VikingOSX

Amazing, thank you so much. Simple fix.


I have three folders in total that will renaming: CFCXXX_CAMA, CFCXXX_CAMB, CFCXXX_CAMC.


Could this all be renamed by running one application?


Currently I have three separate applications saved and I run them one at a time?


I have it as three separate applications because when I tried it in one and pressed run, all files got renamed to the last prefix CAMC.

Oct 19, 2024 4:14 PM in response to tprloveridge

Yes, Import has a folder hierarchy within it. The new application would present you with Ask For Finder Items (folders) with multiple selection. You would then double-click the Import folder to reveal, and then select in order: CAMA CAMB CAMC using the ⌘-key for multiple folder selection.


I would then assign the customerRef to a variable, remove it from the list of arguments provided to the Run Shell Script action, and then use a for loop on the remaining folder selections whose name, I would use as part of the sequential filenaming in that respective folder. Fun stuff.

Automator: change files names and replace XXX

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