我想在目录中搜索与任何单词列表匹配的任何文件。如果文件匹配,我想将该文件复制到新目录中。我创建了一小批测试文件并让以下代码正常工作:
cp `grep -lir 'word\|word2\|word3\|word4\|word5' '/Users/originallocation'` '/Users/newlocation'
不幸的是,当我在一个包含数千个文件的大文件夹上运行此代码时,它说参数列表对于 cp
来说太长了。我想我需要循环这个或使用 xargs
但我不知道如何进行转换。
最佳答案
与您所拥有的最小变化是:
grep -lir 'word\|word2\|word3\|word4\|word5' '/Users/originallocation' | \
xargs cp -t '/Users/newlocation'
但是,不要使用它。因为您永远不知道什么时候会遇到包含空格或换行符的文件名,所以应该使用以 null 结尾的字符串。在 linux/GNU 上,将 -Z 选项添加到 grep 并将 -0 添加到 xargs:
grep -Zlir 'word\|word2\|word3\|word4\|word5' '/Users/originallocation' | \
xargs -0 cp -t '/Users/newlocation'
在 Mac(以及 AIX、HP-UX、Solaris、*BSD)上,grep 选项略有变化,但更重要的是,GNU cp -t 选项不可用。解决方法是:
grep -lir --null 'word\|word2\|word3\|word4\|word5' '/Users/originallocation' | \
xargs -0 -I fname cp fname '/Users/newlocation'
这效率较低,因为必须为每个要复制的文件运行一个新的 cp
实例。
关于bash - 扩展 grep find 并复制到大文件夹(xargs?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21445250/