Recursive copy of specific files in Unix/Linux?

Yury Pogrebnyak picture Yury Pogrebnyak · Mar 8, 2012 · Viewed 77.4k times · Source

I need to copy all *.jar files from directory and all its subdirectories. How can I do it in UNIX/Linux terminal? Command cp -r *.jar /destination_dir doesn't work.

Answer

Sean picture Sean · Mar 8, 2012

rsync is useful for local file copying as well as between machines. This will do what you want:

rsync -avm --include='*.jar' -f 'hide,! */' . /destination_dir

The entire directory structure from . is copied to /destination_dir, but only the .jar files are copied. The -a ensures all permissions and times on files are unchanged. The -m will omit empty directories. -v is for verbose output.

For a dry run add a -n, it will tell you what it would do but not actually copy anything.