Linux: How to mass rename/edit filenames
The problem:
Most of us when we want to rename files in Linux we use the ‘mv’ command, which its not really made to rename files but rather to move them to another directory. It can however to rename the file as the destination parameter but since the ‘mv’ command its not made to to rename files its capabilities are limited when it comes to mass file operations, you cant do something like this:
$ mv *.txt_back *.txt
mv: target '*.txt' is not a directory
The solution:
But Linux has almost solutions for everything, there is a very handy tool called ‘rename’, if the tool not installed you can install it (at least in a Debian based system) with the following command:
$ sudo apt-get install rename
How to use rename:
rename used regular expressions to match filenames and change them, the general format of the command is:
rename "regex" files
Example: how to change the file extension
$ rename 's/.txt/.txt_back/' *.txt
Example: How to change/delete prefix of files
$ ls
a_1.txt a_2.txt a_3.txt
To remove a_ from txt files
$ rename 's/^a_//' *.txt
Then
$ ls
1.txt 2.txt 3.txt
To append b_ prefix to txt files
$ rename 's/^/b_/' *.txt
$ ls
b_1.txt b_2.txt b_3.txt
Example: How to change/delete postfix of files
$ ls
1.txt 2.txt 3.txt
$ rename 's/$/\_bk/' *.txt
$ ls
b_1.txt_bk b_2.txt_bk b_3.txt_bk
Example: How to replace spaces with underscores in filenames
$ ls -l
'this is a file with spaces 1.txt'
'this is a file with spaces 3.txt'
'this is a file with spaces 2.txt'$ rename 's/ /\_/g' *.txt
$ ls -l
this_is_a_file_with_spaces_1.txt
this_is_a_file_with_spaces_3.txt
this_is_a_file_with_spaces_2.txt
Note: the ending ‘g’ in the regular expression means do the change globally, if you omit this it will replace the first space of each file with an underscore.
I hope you find the article interesting :)