Recursive copy of specific files in Unix/Linux? [closed]

痞子三分冷 提交于 2019-12-17 17:25:26

问题


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.


回答1:


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.




回答2:


If you don't need the directory structure only the jar files, you can use:

shopt -s globstar
cp **/*.jar destination_dir

If you want the directory structure you can check cp's --parents option.




回答3:


If your find has an -exec switch, and cp an -t option:

find . -name "*.jar" -exec cp -t /destination_dir {} +

If you find doesn't provide the "+" for parallel invocation, you can use ";" but then you can omit the -t:

find . -name "*.jar" -exec cp {} /destination_dir ";"



回答4:


tar -cf - `find . -name "*.jar" -print` | ( cd /destination_dir && tar xBf - )



回答5:


cp --parents `find -name \*.jar` destination/

from man cp:

--parents
       use full source file name under DIRECTORY



回答6:


If you want to maintain the same directory hierarchy under the destination, you could use

(cd SOURCE && find . -type f -name \*.jar -exec tar cf - {} +) \
  | (cd DESTINATION && tar xf -)

This way of doing it, instead of expanding the output of find within back-ticks, has the advantage of being able to handle any number of files.




回答7:


find . -name \*.jar | xargs cp -t /destination_dir

Assuming your jar filenames do not contain spaces, and your cp has the "-t" option. If cp can't do "-t"

find . -name \*.jar | xargs -I FILE cp FILE /destination_dir


来源:https://stackoverflow.com/questions/9622883/recursive-copy-of-specific-files-in-unix-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!