How to copy files found with grep

六月ゝ 毕业季﹏ 提交于 2019-12-31 01:41:08

问题


I am running this command to find all my files that contain (with help of regex)"someStrings" in a tree directory.

grep -lir '^beginString' ./ -exec cp -r {} /home/user/DestinationFolder \; 

It found files like this:

FOLDER
a.txt
-->SUBFOLDER
  a.txt
---->SUBFOLDER
     a.txt

I want to copy all files and folder, with the same schema, to the destination folder, but i don't know how to do it. It's important copy files and folder, because several files found has the same name and I need to keep it.


回答1:


Try this:

find . -type f -exec grep -q '^beginString' {} \; -exec cp -t /home/user/DestinationFolder {} +

or

grep -lir '^beginString' . | xargs cp -t /home/user/DestinationFolder

But if you want to keep directory structure, you could:

grep -lir '^beginString' . | tar -T - -c | tar -xpC /home/user/DestinationFolder

or if like myself, you prefer to be sure about kind of file you store (only file, no symlinks), you could:

find . -type f -exec grep -l '^beginString' {} + | tar -T - -c |
    tar -xpC /home/user/DestinationFolder


来源:https://stackoverflow.com/questions/37396487/how-to-copy-files-found-with-grep

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