扩展grep查找并复制到大文件夹(xargs?)

时间:2014-01-29 23:54:34

标签: bash grep xargs cp

我想在目录中搜索与任何单词列表匹配的任何文件。如果文件匹配,我想将该文件复制到新目录中。我创建了一小批测试文件并获得以下代码:

cp `grep -lir 'word\|word2\|word3\|word4\|word5' '/Users/originallocation'` '/Users/newlocation'

不幸的是,当我在一个包含几千个文件的大文件夹上运行此代码时,它说参数列表对cp来说太长了。我想我需要循环播放或使用xargs,但我无法弄清楚如何进行转换。

2 个答案:

答案 0 :(得分:3)

与你所拥有的最小变化是:

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的新实例。

答案 1 :(得分:1)

没有grep -r的人的替代解决方案。使用find + egrep + xargs,希望不同文件夹中没有相同文件名的文件。其次,我取代了word\|word2\|word3\|word4\|word5

的丑陋风格
find . -type f -exec egrep -l 'word|word2|word3|word4|word5' {} \; |xargs -i cp {}  /LARGE_FOLDER