Skip to content

[Linux] Rename a Large Number of Files With “rename” Command (Regular Expression)

Last Updated on 2021-10-23 by Clay

If we want to rename a large number of files in batches, in addition to writing script to use mv command, we can also use rename command to set a rule to match the file name (just like regular expression) to rename.

However, the built-in rename command is difference on different systems. In addition to referring to the record below, you also need to test on your environment.


Install rename

Ubuntu

apt install rename


CentOS(prename: perl-rename)

yum install prename


MacOS

brew install rename

The usage of rename command

Basic usage

rename "s/STRING/NEW_STRING/" FILEs


Before renaming the file, you can use the -n to view the renamed result. Assuming I have three files F1, F2, F3, etc. I can use the following command to show the rename results:

rename -n "s/F/X/" *


Output:

'F1' would be renamed to 'X1'
'F2' would be renamed to 'X2'
'F3' would be renamed to 'X3'


You can show the rename results without really do that. (Note: * is mean the all files under the directory)



Insert string on the left (Use ^ symbol)

rename "s/^/A/" *


Output:

AF1  AF2  AF3




Insert string on the right (Use $ symbol)

rename "s/$/_/" *


Output:

AF1_  AF2_  AF3_



Delete the match string

rename "s/A//" *
rename "s/_//" *


Output

F1  F2  F3

References


Read More

Tags:

Leave a Reply