Trim filenames in automator w. shell or applescript

applescriptautomatorcommand line

Why doesn't this work?

(The automator is in swedish but the parts are:
get selected finder objects –
get folder contents –
run shell script)

Printscreen Automator

I want to trim the first three characters of the filenames in a folder as part of an automator folder action.
I don’t know shell scripting myself, but I’ve read around quite a bit and think this should do the trick.

I've also tried this with applescript:
Automator Applescript

It works better but only with the first 8 files for some reason.

Does someone know how to sort this out?
/Daniel

Best Answer

The reason your shell script isn't doing what you want is because Automator passes the full path of the files as arguments.

If the full path to one of the files is /Users/foo/Temp/file1.txt, then your script attempts to rename it to ers/foo/Temp/file1.txt, which isn't what you want.

Try this instead:

for f in "$@"; do
  FILENAME=$(basename "$f")
  DIRNAME=$(dirname "$f")
  mv "$f" "${DIRNAME}/${FILENAME:3}"
done

Better still (handles relative filenames correctly):

for f in "$@"; do
  FILENAME=$(basename "$f")
  DIRNAME=$(dirname "$f")
  if [ -z "$DIRNAME" ]; then
    DIRNAME="."
  fi
  mv "$f" "${DIRNAME}/${FILENAME:3}"
done