Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename files using math operations

I am trying to rename some files using a bash command, but I don't know how to add an arithmetic expression/math operation into the regex expression.

Input:

a000.png
a001.png
...

Ouput:

a010.png
a011.png
...

I am trying to add 10 to the names.

Some things I tried:

rename -n -e 's/a(\d+).png/a$1 + 10.png/' *
rename -n -e 's/a(\d+).png/a{$1 + 10}.png/' *
rename -n -e 's/a(\d+).png/a$($1 + 10).png/' *

Is there a simple way to do this?

like image 976
klaus Avatar asked Dec 12 '17 23:12

klaus


1 Answers

This should do the trick. If you do not want the leading zero you can remove sprintf as well as the "%03d" format string. Furthermore, if the files to be renamed will always begin with a, you can also supplant the leading regex [a-zA-Z]* with the literal character a. Lastly, although the * file specifier may be adequate, I would recommend tacking on an extension as an additional safety precaution (e.g. *.png).

As always, try it out first using the -n flag to verify the rename is correct.

rename -v 's/([a-zA-Z]*)([0-9]*)/$1.sprintf("%03d",$2+10)/e' *
like image 179
Travis Clarke Avatar answered Oct 07 '22 20:10

Travis Clarke