4

How can I remove the last 12 characters of all files' filenames in a certain directory via Terminal?

7

Using bash parameter expansion:

for i in ?????????????*; do echo mv -i "$i" "${i%????????????}"; done

remove echo for actual action. Check for same output filename for multiple source files.

Also you could use parameter expansion replacement pattern:

for i in ?????????????*; do echo mv -i "$i" "${i/????????????}"; done

Using rename (prename), from that directory:

rename -n 's/.{12}$//' *

This will rename all files and directories, if you want to do for only files:

find . -maxdepth 1 -type f -name '?????????????*' -exec rename -n 's/.{12}$//' {} +

This will do dry-running, remove -n for actual action:

find . -maxdepth 1 -type f -name '?????????????*' -exec rename 's/.{12}$//' {} +

Again this could result in a race condition, make sure you check the output from the dry-running carefully.

| improve this answer | |
  • Thanks! I forgot to mention to ignore the file-extension, so there is a cleaner solution to my problem. I eventually appended that via pyRenamer without difficulty as I'm exclusively dealing with files of the same type. – Markus Gratis Jan 19 '17 at 8:50
3

You could use rename. From inside the directory:

rename -n 's/(.*).{12}/$1/' *

Remove -n after testing to actually rename the files. Replace {12} with {whatever number of characters you want to delete from the end of the name}

Explanation

  • s/old/new/' replace oldwithnew`
  • (.*) save any number of any characters...
  • .{12} the last twelve characters whatever they are
  • $1 the characters saved with ()
| improve this answer | |

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.