[英]Find Files Containing Certain String and Copy To Directory Using Linux
I am trying to find files that contain a certain string in a current directory and make a copy of all of these files into a new directory.我试图在当前目录中查找包含某个字符串的文件,并将所有这些文件复制到一个新目录中。
My scrip that I'm trying to use我正在尝试使用的脚本
grep *Qtr_1_results*; cp /data/jobs/file/obj1
I am unable to copy and the output message is:我无法复制,输出消息是:
Usage: cp [-fhipHILPU][-d|-e] [-r|-R] [-E{force|ignore|warn}] [--] src target
or: cp [-fhipHILPU] [-d|-e] [-r|-R] [-E{force|ignore|warn}] [--] src1 ... srcN directory
Edit: After clearing things up (see comment)...编辑:清理后(见评论)...
cp *Qtr_1_results* /data/jobs/file/obj1
What you're doing is just greping for nothing.你正在做的只是一无所获。 With ;
与;
you end the command and cp
prints the error message because you only provide the source, not the destination.您结束命令并cp
打印错误消息,因为您只提供源,而不是目标。
What you want to do is the following.您想要做的是以下内容。 First you want to grep for the filename, not the string (which you didn't provide).首先,您要搜索文件名,而不是字符串(您没有提供)。
grep -l the_string_you_are_looking_for *Qtr_1_results*
The -l
option gives you the filename, instead of the line where the_string_you_are_looking_for
is found. -l
选项为您提供文件名,而不是找到the_string_you_are_looking_for
的行。 In this case grep
will search in all files where the filename contains Qtr_1_results
.在这种情况下, grep
将搜索文件名包含Qtr_1_results
所有文件。
Then you want send the output of grep
to a while
loop to process it.然后你想将grep
的输出发送到一个while
循环来处理它。 You do this with a pipe ( |
).您可以使用管道 ( |
) 执行此操作。 The semicolon ;
分号;
just ends lines.只是结束行。
grep -l the_string_you_are_looking_for *Qtr_1_results* | while read -r filename; do cp $filename /path/to/your/destination/folder; done
In the while
loop read -r
will put the output of grep
into the variable filename
.在while
循环中read -r
会将grep
的输出放入变量filename
。 When you assing a value to a variable you just write the name of the variable.当您为变量赋值时,您只需写出变量的名称。 When you want to have the value of the variable, you put a $
in front of it.当你想拥有变量的值时,你在它前面放一个$
。
You can use multiple exec in find to do this task您可以在 find 中使用多个 exec 来完成此任务
For eg:例如:
find . -type f -exec grep -lr "Qtr_1_results" {} \; -exec cp -r {} /data/jobs/file/obj1 \;
Details:细节:
Find all files that contains the string.查找包含该字符串的所有文件。 grep -l will list the files. grep -l 将列出文件。
find . -type f -exec grep -lr "Qtr_1_results" {} \;
Result set from first part is a list of files.第一部分的结果集是文件列表。 Copy each files from the result to destination.将每个文件从结果复制到目标。
-exec cp -r {} /data/jobs/file/obj1 \;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.