Ubuntu – Pattern based, batch file rename in terminal

batch-renameregexrename

I need to rename the following:

file_001_loremipsum.png
file_002_dolor.png
file_003_sit.png
file_004_amet.png
file_105_randomness.png

into

upl_loremipsum.png
upl_dolor.png
upl_sit.png
upl_amet.png
upl_randomness.png

How do I make it happen with just one simple line of terminal command?

Best Answer

The solution to the above example, using rename:

rename -v -n 's/file_\d{1,3}/upl/' file_*.png

Usage:

rename [options] [Perl regex search/replace expression] [files]

From man rename:

   -v, --verbose
           Verbose: print names of files successfully renamed.
   -n, --no-act
           No Action: show what files would have been renamed.

rename MAY take regex as the arguments.

What we are looking at is the content between the single quotes '. You can place regex separated by /.

Formula: s/(1)/(2)/ where (1) = search pattern, and (2) = replace pattern.

So, familiarize youself with regex, and enjoy pattern based batch file renaming!

Related Question