emporeso
emporeso

Reputation: 11

Moving photos and renaming them if they exist?

I'm trying to move photos from directories to one directory with find. It works good:

find /origin/path \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.JPG' -o -iname '*.JPEG' -o -iname '*.PNG' -o -iname '*.png' -o -iname '*.gif' -o -iname '*.GIF' \) -type f -exec mv -nv -t /final/path -- {} +;

How to rename files if they have the same name (but different photos)?

Upvotes: 1

Views: 89

Answers (2)

nabeel
nabeel

Reputation: 319

sorry i didn't because i'm on windows now, but below script should do it

files_list=$(find /origin/path \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.JPG' -o -iname '*.JPEG' -o -iname '*.PNG' -o -iname '*.png' -o -iname '*.gif' -o -iname '*.GIF' \) -type f)

for file in ${files_list}
do
    counter=0
    while true
    do
        if [[ ! -a ${file} ]]
        then
            mv "${file}" "/final/path/${file}"
            break
        else
            file="${file}${counter}"
            (( counter++ ))
        fi
    done
done

Upvotes: 0

hlovdal
hlovdal

Reputation: 28198

You can use the --backup=t option for mv. This will append an increasing numbered suffix to files whose target already exists.

$ find /tmp/test -type f
/tmp/test/dir2/image.jpg
/tmp/test/dir3/image.jpg
/tmp/test/dir1/image.jpg
/tmp/test/dir4/image.jpg
$ mkdir /tmp/test2
$ find /tmp/test -iname '*.jpg' -print0 | xargs -0 mv -v --backup=t --target-directory=/tmp/test2
‘/tmp/test/dir2/image.jpg’ -> ‘/tmp/test2/image.jpg’
‘/tmp/test/dir3/image.jpg’ -> ‘/tmp/test2/image.jpg’ (backup: ‘/tmp/test2/image.jpg.~1~’)
‘/tmp/test/dir1/image.jpg’ -> ‘/tmp/test2/image.jpg’ (backup: ‘/tmp/test2/image.jpg.~2~’)
‘/tmp/test/dir4/image.jpg’ -> ‘/tmp/test2/image.jpg’ (backup: ‘/tmp/test2/image.jpg.~3~’)
$

Upvotes: 3

Related Questions