MacOS – How to remove leading/trailing whitespace from filenames in Automator

applescriptautomatormacos

My wife tediously renames files all the time when storing on her backup external storage, so I investigated using automator to do this for her. I now have an automator folder where she just drops the file in there and it will rename the file appropriately.

I'm now faced with a situation where the file may now contain leading and/or trailing whitespace, how might I simply trim this whitespace?

I've never really used AppleScript but am proficient in shell scripting, can I simply write a shell script that will perform this task? I will give AppleScript a go if someone could point me in the right direction.

Best Answer

for f in "$@"; do new="$(echo -n "$f" | sed -E 's|/$||;s| +$||;s|^ +||;s|/ +([^/]+$)|/\1|;s| +(\.[^.][a-zA-Z0-9.]*)$|\1|g')"; mv "$f" "$new"; echo "$new"; done

(Paste as a Run Shell Script action and select Pass input: as arguments.)