Search code examples
linuxshellubuntufile-renamebatch-rename

Removing 10 Characters of Filename in Linux


I just downloaded about 600 files from my server and need to remove the last 11 characters from the filename (not including the extension). I use Ubuntu and I am searching for a command to achieve this.

Some examples are as follows:

aarondyne_kh2_13thstruggle_or_1250556383.mus should be renamed to aarondyne_kh2_13thstruggle_or.mus

aarondyne_kh2_darknessofunknow_1250556659.mp3 should be renamed to aarondyne_kh2_darknessofunknow.mp3

It seems that some duplicates might exist after I do this, but if the command fails to complete and tells me what the duplicates would be, I can always remove those manually.


Solution

  • Try using the rename command. It allows you to rename files based on a regular expression:

    The following line should work out for you:

    rename 's/_\d+(\.[a-z0-9A-Z]+)$/$1/' *
    

    The following changes will occur:

    aarondyne_kh2_13thstruggle_or_1250556383.mus renamed as aarondyne_kh2_13thstruggle_or.mus
    aarondyne_kh2_darknessofunknow_1250556659.mp3 renamed as aarondyne_kh2_darknessofunknow.mp3
    

    You can check the actions rename will do via specifying the -n flag, like this:

    rename -n 's/_\d+(\.[a-z0-9A-Z]+)$/$1/' *
    

    For more information on how to use rename simply open the manpage via: man rename