Bash – Add or subtract a number from the names of all the files in a directory

arithmeticbashfilenamesrename

I have a number of png and jpg files whose names are numbers, e.g.0100.png, in a directory,

  • How can I add 1 to their names, for example, to get 0002.png and 0003.png from 0001.png and 0002.png respectively, without overwriting?

  • How can I subtract 2 from their names, so that 0100.png will not become 098.png but 0098.png instead?

Related https://stackoverflow.com/questions/26770060/subtracting-a-number-from-the-names-of-all-the-files-in-a-directory, but more difficult here.

Best Answer

I would probably end up using temporary directory in this case:

for file in [[:digit:]]*.png; do
    echo mv $file tmp/$(printf %04d $((10#${file%.png}+1))).png
done

The important part is 10#N which forces bash to interpret 000N as just N, otherwise leading zeros denotes octal numbers.

For example:

$ touch 0001.png 0002.png 0010.png 0020.png 0100.png 0200.png
$ for file in [[:digit:]]*.png; do echo mv $file tmp/$(printf %04d $((10#${file%.png}-1))).png; done
mv 0001.png tmp/0000.png
mv 0002.png tmp/0001.png
mv 0010.png tmp/0009.png
mv 0020.png tmp/0019.png
mv 0100.png tmp/0099.png
mv 0200.png tmp/0199.png
Related Question