bash 如何仅移动嵌套子目录中具有特定扩展名的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/11417825/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I move just the files with a particular extension from nested sub-directories?
提问by lovespeed
In a directory I have many sub-directories and each of these sub-directories have many files of different types. I want to extract all the files with a particular extension from each subdirectory and put it in a different folder. Is it possible to write a bash script to do this? If so how?
在一个目录中,我有许多子目录,每个子目录都有许多不同类型的文件。我想从每个子目录中提取具有特定扩展名的所有文件并将其放在不同的文件夹中。是否可以编写 bash 脚本来执行此操作?如果是这样怎么办?
回答by vergenzt
$ find <directory> -name '*.foo' -exec mv '{}' <other_directory> \;
finddoes a recursive search through a directory structure and performs the given actions on any files it finds that match the search criteria.
find通过目录结构进行递归搜索,并对它找到的与搜索条件匹配的任何文件执行给定的操作。
In this case, -name '*.foo'is the search criteria, and -exec mv '{}' <other_directory> \;tells findto executemvon any files it finds, where '{}'is converted to the filename and \;represents the end of the command.
在这种情况下,-name '*.foo'是搜索条件,并-exec mv '{}' <other_directory> \;告诉在它找到的任何文件find上执行mv,其中'{}'转换为文件名并\;表示命令的结尾。
回答by novacik
If you have bash v4 and have
如果你有 bash v4 并且有
shopt -s globstar
in your .profile, you can use:
在您的 .profile 中,您可以使用:
mv ./sourcedir/**/*.ext ./targetdir
回答by Arnaud Le Blanc
Using find and a simple while loop whould do it:
使用 find 和一个简单的 while 循环可以做到:
find directory -name '*.foo'|while read file; do
    mv $file other_directory/
done
Here it will move all files with a .foosuffix to other_directory/
在这里它将所有带有.foo后缀的文件移动到 other_directory/
回答by Todd A. Jacobs
You can use findand xargsto reduce the need for loops or multiple calls to mv.
您可以使用find和xargs来减少对循环或多次调用mv 的需要。
find /path/to/files -type f -iname \*foo -print0 |
    xargs -0 -I{} mv {} /path/to/other/dir

