问题描述
我正在运行此命令以在树目录中查找包含(借助正则表达式)someStrings"的所有文件.
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 ;
它找到了这样的文件:
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.
推荐答案
试试这个:
find . -type f -exec grep -q '^beginString' {} ; -exec cp -t /home/user/DestinationFolder {} +
或
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
如果您的文件名可以包含空格和/或特殊字符,请使用空终止字符串
来传递grep -l
输出 (arg -Z
) 到 tar -T
(arg --null -T
):
and if your files names could countain spaces and/or special characters, use null terminated strings
for passing grep -l
output (arg -Z
) to tar -T
(arg --null -T
):
find . -type f -exec grep -lZ '^beginString' {} + | tar --null -T - -c |
tar -xpC /home/user/DestinationFolder
这篇关于如何复制用grep找到的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!