bash 如何复制用grep找到的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37396487/
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 to copy files found with grep
提问by user6372336
I am running this command to find all my files that contain (with help of regex)"someStrings" in a tree directory.
我正在运行此命令以在树目录中查找包含(在正则表达式的帮助下)“someStrings”的所有文件。
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.
我想将具有相同架构的所有文件和文件夹复制到目标文件夹,但我不知道该怎么做。复制文件和文件夹很重要,因为找到的几个文件具有相同的名称,我需要保留它。
回答by F. Hauri
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