[AUTOMATOR] - Rename Files in SubFolders by adding "_(ParentFolderName)" recursively in order
After testing the previous solution by the great VikingOSX here: [AUTOMATOR] - Rename Files in SubFolders … - Apple Community
Only the version 2021-10-18 works but the file names unfortunately are set in the opposite order desired.
Does someone know how to invert the order?
Like: Advertiser_Language_CodeName_LifeStyle_Video_filename
Here is the working code.
#!/bin/zsh
: <<'COMMENT'
Rename every jpg|png|gif|mp4|zip files in the selected parent folder hierarchy to embed the
parent folder name as a prefix to the individual document name.
Usage: Select one or more folders in the Finder for the QA to process
Tested: Zsh 5.8 on macOS 11.6
VikingOSX, 2021-10-18, Apple Support Communities, No warranties at all.
COMMENT
typeset -gi stime=0 etime=0 elapsed=0 parcnt=0 fcnt=0
function finished () {
osascript <<-AS
use scripting additions
display dialog "Parent folders: $1" & return & "Files: $2" & return & "Time: $3" with title "Processing Complete"
return
AS
return
}
#start time
stime=$(date -j -u +%s)
# process all selected parents
for parent in "${@}";
do
(( parcnt++ ))
# path to every doc with the extensions below in the parent's subfolders
for sub in ${parent}/**/*.(jpg|png|gif|mp4|zip)(.N);
do
# skip files that already have parent folder prefix
[[ "${sub:a:r:t}" =~ "^(${parent:t})_.*" ]] && continue
# print "${sub:a:h:r}/${parent:t}_${sub:t}"
# rename to subfolder/basename_parentfolder.ext
mv "${sub}" "${sub:a:h:r}/${parent:t}_${sub:t}"
(( fcnt++ ))
done
done
# end time
etime=$(date -j -u +%s)
elapsed=$(( etime - stime ))
# only show dialog when files have been processed
(( fcnt )) && $(finished ${parcnt} ${fcnt} "$(date -j -u -f "%s" "${elapsed}" +%T)")
exit 0
Thanks,
MacBook Pro 17″, OS X 10.11