Search code examples
linuxbashshellfile-rename

How to rename all the files and no overwriting?


I know how to rename all the files in the folder with numbers:

i=1
for f in *.jpg
do
    NEW_NAME=$( printf "%05d.jpg" $i )
#   echo mv "$f" "$( printf "%05d.jpg" $i )"
    mv -n "$f" "$NEW_NAME"
    ((i++))
done

So all my files will be renames, but if I have a file like 0004.jpg, it will not rename the file as n+1. I have tried to add a loop for increasing i if the name exists:

i=1
for f in *.jpg
do
    NEW_NAME=$( printf "%05d.jpg" $i )
#   echo mv "$f" "$( printf "%05d.jpg" $i )"
    mv -n "$f" "$NEW_NAME"
    MV=$?
    while [ $MV -ne 0 ]
    do
        ((i++))
        NEW_NAME=$( printf "%05d.jpg" $i )
        mv -n "$f" "$NEW_NAME"
        MV=$?       
    done
    ((i++))
done

but it seems not to work. Any help please?


Solution

  • Your problem is that mv -n returns zero even when the file already exists.

    I'd be tempted to do this:

    i=1
    mkdir .newnames
    for f in *.jpg
    do
        NEW_NAME=$( printf "%05d.jpg" $i )
    #   echo mv "$f" "$( printf "%05d.jpg" $i )"
        mv "$f" ".newnames/$NEW_NAME"
        ((i++))
    done
    mv .newnames/* .
    rmdir .newnames
    

    Basically, by moving the files into a temporary directory (the leading . (dot) prevents the for loop trying to rename it) you remove the potential for filename clashes.