Search code examples
linuxbashshellshradix

shifting the file name with bash adding a constant number


I have some files named:

0001.jpg
0002.jpg
...
0050.jpg

I need to increment that number by 35, so that I obtain:

0036.jpg
0037.jpg
...
0085.jpg

I thought of trying the following:

for i in {0001..0050}; do
  mv -n $i $((i+35)) 
done

However I get the error bash: 0008: value too great for base (error token is "0008"). I'm not sure I understand what the base means here or how to get around it. I have seen this question. Although it explains the octal error, it is not immediately clear how it helps to iterate with a shifted index.


Solution

  • Problem is that bash arithmetic treats numbers starting with 0 as octal number and only 0-7 digits are allowed in octal system. You can prefix 10# before number to tell bash to accept given number as base 10 number and computer your sum.

    You may use:

    for i in {0010..0001}.jpg; do
       f="${i%.jpg}"
       echo mv "$i $(printf '%04d' $((10#$f + 10#35))).jog"
    done
    

    Once you're satisfied with output, remove echo before mv.

    mv 0010.jpg 0045.jog
    mv 0009.jpg 0044.jog
    mv 0008.jpg 0043.jog
    mv 0007.jpg 0042.jog
    mv 0006.jpg 0041.jog
    mv 0005.jpg 0040.jog
    mv 0004.jpg 0039.jog
    mv 0003.jpg 0038.jog
    mv 0002.jpg 0037.jog
    mv 0001.jpg 0036.jog