Ubuntu – How to batch rename files with terminal

batch-renamecommand line

If I have a set of files like:

1-3-Image Export-08_s3c1.jpg

and I would like to rename the first part to look something like this, by adding and replacing the first part with 'G2_NR2_replicate2':

G2_NR2_replicate2_s3c1.jpg

How would I batch process this in a terminal?

Best Answer

Run the below rename command inside the directory where all the .jpg files are located,

rename 's/^[^_]*(.*)$/G2_NR2_replicate2\1/' *.jpg

It renames all the files which are in the format(name),

1-3-Image Export-08_s3c1.jpg
1-3-Image Export-08_s3c2.jpg
......
1-3-Image Export-08_s3c1000.jpg

to

G2_NR2_replicate2_s3c1.jpg
G2_NR2_replicate2_s3c2.jpg
.....
G2_NR2_replicate2_s3c1000.jpg

Explanation:

's/^[^_]*(.*)$/G2_NR2_replicate2\1/'

  1. rename command works same as sed command.(s/pattern/replace/)

  2. In the pattern part, we give the pattern as ^[^_]*(.*)$

    • ^ --> starting point

    • [^_]* --> Matches any character except _ zero or more times. So it matches upto 1-3-Image Export-08 and whaterver character(s3c1) comes after this part are catched and stored it into a group which was represented by this pattern (.*)$.

    • Now in the replacement part, we place the text given by the op (G2_NR2_replicate2) plus the catched group.

  3. Finally the rename command performs the whole operation.