Linux: How to mass rename/edit filenames

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

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

rename used regular expressions to match filenames and change them, the general format of the command is:

rename "regex" files
$ rename 's/.txt/.txt_back/' *.txt
$ ls
a_1.txt a_2.txt a_3.txt

To remove a_ from txt files

$ rename 's/^a_//' *.txt


$ 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
$ ls
1.txt 2.txt 3.txt
$ rename 's/$/\_bk/' *.txt
$ ls
b_1.txt_bk b_2.txt_bk b_3.txt_bk
$ 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

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 :)

Written by

DevOps engineer, loves Linux, Python, cats and Amiga computers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store