I'm trying to rename files using tr. The following command nearly works:

for file in ./*; do mv -v "$file" $(echo "$file" | tr ' []' '-' | tr -dc 'A-Za-z0-9_-' | tr '[:upper:]' '[:lower:]'); done

However, the command also strips dot characters. So, this file:

St Nicholas' church from NE [1235] 1936-08-01.jpg



I've tried various ways to escape the dot, for instance using tr -dc 'A-Za-z0-9\._-' and tr -dc "A-Za-z0-9\._-"

The result invariably is that every character gets deleted. So my question, how to properly escape dot character in tr -dc?

  • You shouldn't need to escape the dot. tr doesn't use regular expressions. – Kusalananda Dec 30 '16 at 15:55
  • @Kusalananda Hmmm, but if I don't escape the dot everything is deleted as well. – rkhff Dec 30 '16 at 15:58
  • Not when I try it... – Kusalananda Dec 30 '16 at 16:01

Just add the dot in the "allowed characters" set. Also add the / character (part of the path).

for f in ./*; do
  new_f="$( printf "%s" "$f" | tr ' []' '-' | tr -dc 'A-Za-z0-9_./-' | tr '[:upper:]' '[:lower:]')"
  printf "Would move '%s' to '%s'\n" "$f" "$new_f"

This results in

Would move './St Nicholas' church from NE [1235] 1936-08-01.jpg' to './st-nicholas-church-from-ne--1235--1936-08-01.jpg'
  • Ah, yes - adding the '/' that did the trick! Never crossed my mind. Thanks a million. – rkhff Dec 30 '16 at 16:08
  • 1
    @rkhff Yes, I wasn't quite sure what you meant by "deleted". You either meant that the filename became empty, or that the files appeared to be deleted. In the second case, have a look to see if you now have a bunch of "hidden" files laying around (ls -a) whose filenames begin with a dot. – Kusalananda Dec 30 '16 at 16:16
  • Yep, lots of dot files in the directory - so the files appeared to have been deleted. – rkhff Dec 30 '16 at 16:40
  • @rkhff Just "appears" to have been deleted. They were renamed with the leading part of the path (./) changed to .. – Kusalananda Dec 30 '16 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.