Bash Rename – How to Increment a Number Within the Filename

bashrename

I have a directory which contains numbered image files, something like this:

01.png
02.png
03.png
03.svg
04.png
05.png
06.jpg
07.png
08.png
09.png
09.svg
10.png

Sometimes there may be multiple versions of a file in different formats (eg. a png and svg version of the 03 and 09 files above) but the numbers are otherwise consecutive. Typically there are 40-80 such files in each directory. The numbers correspond to the order these images appear in a manuscript (a Word document, but that's not important). There is no other way to determine the order of the images.

If I add a new image to the manuscript I need to place a copy of the image in this directory with the correct numbering. So if the new image is the fifth in the manuscript I need to rename the files in the directory to this in order to make room for it:

01.png
02.png
03.png
03.svg
04.png
06.png
07.jpg
08.png
09.png
10.png
10.svg
11.png

What is the most straightforward way from the command line, or from a script or macro to renumber all the files starting at a certain number? I have a standard Fedora Linux install using bash.

Best Answer

I think that it should do the work:

#!/bin/bash

NEWFILE=$1

for file in `ls|sort -g -r`
do
    filename=$(basename "$file")
    extension=${filename##*.}
    filename=${filename%.*}

    if [ $filename -ge $NEWFILE ]
    then
        mv "$file" "$(($filename + 1))".$extension
    fi
done

Script takes one parameter - number of you new image.

PS. Put script in another directory than your images. In images directory there should be only images named in this way that you described.

Related Question