rename command is mostly used to rename multiple files. The tool searches for a given string in filenames and renames that file with the given new string.
Sample syntax of rename :
$ rename 's/string/other-string/' <files>
$ rename 's/text/txt/' *
After running the command and see your terminal, all the filenames which have ‘text’ in them, that ‘text’ part is replaced with ‘txt’. We used the asterisk sign, meaning we want to rename all files matching the expression.
To match a particular extension:
$ rename 's/string/other string/' *.<extension>
$ rename 's/cat/dog/' *.txt
All files that have ‘.txt’ at their end (ie file’s extension is txt), and have some texts in the name that matches ‘cat’, this ‘cat’ part is replaced with ‘dog’.
Here : Above two examples the strings used were present only at the end of the file name. But this example is different.
$ rename 's/txt/bbb/' atxt.txt
Only the first occurrence of the search string is replace here.
A Global Replacement
In the above example, only the first ‘txt’ was replace in ‘atxt.txt’. To replace both the ‘txt’ we can use a global replacement ‘g’.
$ rename 's/string/other-string/g'
$ rename 's/txt/TXT/g' atxt.txt
After running the command, notice your terminal and files in the directory, both the ‘txt’ are replace with ‘TXT’.
Case Insensitive Replacement
case insensitive replacement, a string can be replace with a case insensitive string.
$ rename 's/string/other string/i'
$ rename 's/.text/.txt/i' *
After running the command, notice your terminal and files in the directory, all ‘.text’ are replace with ‘.txt’.