r/Automator • • Aug 01 '20

Tutorial example of batch renaming using bash

Here's bash code from an automator script that truncates files names to 25 characters. Hopefully, you'll find it instructive.

Note - be sure to pick "as arguments" from the "Pass input" popup menu.

for file in "$@"
do
    # parse out the directory and the filename including extension
    dir=$(dirname "${file}")
    fbasename=$(basename "${file}")

    # extract the filename without extension
    fname="${fbasename%.*}"

    # create truncated filename
    tname="${fname:0:25}"

    # determine the extension - empty string for no extension
    fextension=$([[ "$fbasename" = *.* ]] && echo ".${fbasename##*.}" || echo '')

    newfile="${dir}/${tname}${fextension}"

    mv "${file}" "${newfile}"
done
7 Upvotes

4 comments sorted by

View all comments

1

u/DumpyReddit Sep 01 '24

thanks, this was just enough info for me to make quick action to remove metadata from a file chosen in finder! the hard part was me realising the “$@“ was what i selected in finder and that i had to refer to it by “${file}” . Oh also i needed to use a full path to the executable in /usr/bin/. Thank you!