Remove last n characters of filenames for all files in a directory

29,954

Solution 1

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.

Solution 2

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 ()
Share:
29,954

Related videos on Youtube

Markus Gratis
Author by

Markus Gratis

Updated on September 18, 2022

Comments

  • Markus Gratis
    Markus Gratis almost 2 years

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

  • Markus Gratis
    Markus Gratis over 7 years
    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.