Search code examples
macosbsd

Problems using find and cp to copy just .jpg files from a LOT of directories to one new path


I tried the search, but couldn't find the answer to my specific problem. When I use,

find /recovered_files "*.jpg" -type f -exec cp {} /out \;

to copy all .jpg files from directories within the /recovered_files directory, the /out directory gets filled with every single file (jpg, txt, xml etc etc) from within the source directories. Can anyone please explain wherein my stupidity lies, pleeeeeease???

Many thanks, Mark.


Solution

  • What you're doing at the moment is equivalent to calling cp /dir/dir/dir/file.jpg /out for each file, which will copy the file into /out. Thus, all of the files are being put into the same directory.

    rsync allows filters to select only certain files to be copied. Change from and to to the appropriate directories in the following:

    rsync -r from/* to --include=*.jpg --filter='-! */' --prune-empty-dirs
    

    Credit to this post for this solution.

    Edit: changed to rsync solution. Original as follows:

    find from -name "*.jpg" -type f -exec mkdir -p to/$(dirname {}) \; -exec cp --parents {} to \;
    

    You should replace from and to with the appropriate locations, and this form won't quite work if from begins with /. Just cd to / first if you need to. Also, you'll end up with all the files inside to underneath the entire directory structure of from, but you can just move them back out again.