简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM