Search code examples
linuxbashrenamefile-renamemv

Bash rename with logical-mathematical operations


I have files with the following naming-logic .JPEG (old cameras). e.i., DSC01415.JPEG.

My riddle has been that I would like to make something like:

mv DSC{1415..4131}.JPEG DSC{0001..3517}.JPEG

Which has equal effect of, for any file:

mv DSC<number>.JPEG DSC<number-less-1414>.JPEG

Solution

  • Would you please try the following:

    for ((i = 1415; i <= 4131; i++)); do
        oldname=$(printf "DSC%04d.JPEG" "$i")
        newname=$(printf "DSC%04d.JPEG" "$((i - 1414))")
        if [[ -f $oldname && ! -f $newname ]]; then
            echo mv -- "$oldname" "$newname"
        fi
    done
    

    If the output looks good, drop the echo.
    Please make sure to create the backup before execution not to lose your precious pictures by accident.