Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a top folder with many sub-folders. It's named "a". There are many .png and .jpg files in there. I'd like to recursively copy "a" into a new folder "b", but only copy the .png and .jpg files. How do I achieve that?

share|improve this question
2  
rsync -a --include='*.png' --include='*.jpg' --include='*/' --exclude='*' a/ b/ If you want to prune empty dirs add the -m switch : rsync -am .... – don_crissti Feb 21 at 20:18
1  
Please specify whether you want to recreate the directory structure (including only the jpg/png files) under b or you just want to recursively search for jpg/png under a and copy them to b ? – don_crissti Feb 21 at 21:02
2  
If you want to copy the directory tree recursively, this is a duplicate of unix.stackexchange.com/questions/2161/… . If you want to put all the files directly under b, I can't find a duplicate. Which is it? – Gilles Feb 21 at 21:50
up vote 2 down vote accepted
find a \( -name "*.png" -or -name "*.jpg" \) -exec cp {} b \;
share|improve this answer
    
Whoops, I accidentally used *.png twice and forgot .jpg. This is what happens when I try to answer questions while listening to music. Thanks for catching my mistake. – gardenhead Feb 21 at 20:56
    
OK, I think I got it this time. I learned something new about find today. Thanks. – gardenhead Feb 21 at 21:06
    
One more thing: stick with -o instead of -or, it's more portable. – don_crissti Feb 21 at 21:13
    
thanks you two. – RM1970 Feb 23 at 22:49
for file in $(find a -name "*.jpg" -o -name "*.png")
do
  cp ${file} b/${file}
done
share|improve this answer

One-liner

cp $(find a -name "*.jpg" -o -name "*.png") b
share|improve this answer

Your Answer

 
discard

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.