Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a number of images inside subdirectories of another directory which I'd like to copy to one single directory so all the images are in one place.

After a bit of searching, I found and then modified some things to create this command:

find . -name "z*.jpg" -exec cp '{}' ~/Extracted/ \;

This seemingly worked, however I found that images with the same name would be overwritten, so then I did this:

find . -name "z*.jpg" -exec cp -n '{}' ~/Extracted/ \;

But now images with the same name are simply ignored.

Is there anyway I could do this so every image is copied over and images with the same name are renamed?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Your problem is actually to find a cp variant that creates the target file under a different name if it already exists. I'm not aware of a tool that does so, however, it's not hard to implement yourself:

cp -vn "$1" "$2"/ || cp -vn "$1" "$2"/"${1##*/}"~"$(md5sum "$1" | cut -f1 -d' ')"

This script calls cp again in case it fails, appending the checksum to the filename. Flaw: If a third file with the same name shows up, it will overwrite the second file if they are identical.

Given that the above script is called saveCopy and stored in the parent working directory, the following works:

$ find . -name 'z*.jpg' -exec ./saveCopy {} /tmp/Extracted/ \;
./a/z1.jpg -> /tmp/Extracted/z1.jpg
./a/z2.jpg -> /tmp/Extracted/z2.jpg
./a/z3.jpg -> /tmp/Extracted/z3.jpg
/tmp/Extracted/z3.jpg not overwritten
./b/z3.jpg -> /tmp/Extracted//z3.jpg~d41d8cd98f00b204e9800998ecf8427e
./b/z4.jpg -> /tmp/Extracted/z4.jpg

Be aware that the script only works for a single input file and if the target is a directory! It can certainly be improved ;-)

share|improve this answer
Thanks, this does the job! –  Nysepho Feb 19 '13 at 18:32
Nice, +1. Why would it be a flaw to overwrite identical files? –  terdon Feb 19 '13 at 22:15
@terdon the flaw is actually more that you still end up with 2 copies of an identical file, because the first copy doesn't have the hash attached. It's not consistent. However, I just wanted to keep the example small, if one wants to use something like this on a regular basis one should think of a slightly more sophisticated solution. –  barbaz Feb 20 '13 at 8:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.