5

I have around 200 .png files in my folder, naming like -

02.png
03.png
04.png
...
201.png

As you can see I dont have 01.png so I want to rename the all files decreasing by one, to make it like -

01.png
02.png
03.png
...
200.png

Is it possible it to do it via any command in ubuntu ?

Following is the command I am trying with no luck -

rename -n '/d{2}\.png$d{2}-1\.png/' *.png
  • @JacobVlijm I don't think as starting series is - 01, 02 .. and not like 1, 2 ... – Nesh Sep 23 '15 at 7:14
  • 1
    you might want to refresh your screen, I retracted my vote a while ago, came to the same conclusion :) – Jacob Vlijm Sep 23 '15 at 7:26
6

This can be done with a somewhat more complex rename command:

rename -n 's/(\d{2,3}).png/sprintf("%02d", $1-1) . ".png"/e' *.png

Notes:

  • You need to separate the match and the replacement with a /.
  • You need to group the part you want to remember using $1 with () (in this case (\d{2,3})).
  • You should match both 2- and 3-digit numbers, or 100.png will become 1-1.png.
  • To use an arithmetic or functions in the replacement, it should be evaluated as an expression, that's why there's a e after the closing /.
  • To combine strings in an evaluated expression, you need to use . (hence . ".png").
  • To pad strings with zeros (presumably what you want, since your original files had them), use sprintf. %02d will pad with zeros if your number doesn't have at least two digits.

Example:

$ rename -n 's/(\d{2,3}).png/sprintf("%02d", $1-1) .  ".png"/e' *.png | head
02.png -> 01.png
03.png -> 02.png
04.png -> 03.png
05.png -> 04.png
06.png -> 05.png
07.png -> 06.png
08.png -> 07.png
09.png -> 08.png
100.png -> 99.png
101.png -> 100.png

Depending on the version of rename, it might have trouble renaming files if the target already exists. In such cases, a simple workaround is to create a temporary directory and rename/move the files there:

mkdir temp
rename -n 's/(\d{2,3}).png/sprintf("temp\/%02d", $1-1) . ".png"/e' *.png

Note that / after temp needs to be escaped, or it will be taken as the final / of a s// command.

| improve this answer | |
  • Following is the output for the command - 01.png renamed as 00.png 02.png not renamed: 01.png already exists 03.png not renamed: 02.png already exists – Nesh Sep 23 '15 at 7:17
  • @Nesh make a temp folder and rename+move to that folder: mkdir temp; rename -n 's/(\d{2,3}).png/sprintf("temp\/%02d", $1-1) . ".png"/e' *.png. – muru Sep 23 '15 at 7:19
  • @Nesh edited accordingly. – muru Sep 23 '15 at 7:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.