Normally, when you want to rename a single file, you would use the "mv" command. However, if you have a bunch of files to rename, the faster and more efficient command is "rename".
The syntax of "rename" is quite complicated though, its general form is:
rename 's/old-name/new-name/' filespec
For example, to change all .txt files to .doc, the command will be:
rename 's/txt/doc/' *
This command will change the "txt" part of the file names into "doc". However a problem may occur if the part "txt" also appears in the name of the files. The better command to change .txt file to .doc will be:
rename 's/txt$/doc/' *
This command will change "txt" into "doc" in any file that has "txt" in the end of the file name, which means that if a file with no extension ends with "txt", it will be renamed too. Thats why the best command to change all .txt files to .doc will be:
rename 's/\.txt/\.doc/' *
This command will change all the .txt extensions into .doc without caring about the part before the extension.
Another example is to remove the hyphen("-") before the file names, your command will be:
rename 's/-*//' *
If you have a collection of songs sung by the same singer, to add the singer's name before the name of the mp3 songs, the command will be:
rename 's//singers-name-/' *.mp3
In case you want to remove or change a part that appears multiple times in the file names ( for example, kakarot.png, kanaka.txt, bakaka.mp3 ....), if you use any of the above commands, only the first "ka" will be changed or removed. To remove or change all these "ka", you will need to use the "g" (global) option. For example,the command to remove all the "ka" in the name of all files will be:
rename 's/ka//g' *
With this command, all the "ka" parts will be erased from the name of all files in the current folder.
- Since the syntax of rename is complicated, you may very likely make mistakes. If you want to make sure everything is right, you should use the "-n" parameter (means "no action") first with rename to check the output. The command will be like this:
rename -n 's/ka//g' *
The output of the rename command will be displayed in the terminal but nothing is changed. If everything looks good, you can run the actual command without "-n".
- Besides the "s" option ( means substitute), "y" (means translate) is another thing you can try with rename. For example, to convert all the file names from low letters to capital letters, you can use this command:
rename 'y/A-Z/a-z/' *