简体   繁体   中英

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.

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. In this case grep will search in all files where the filename contains Qtr_1_results .

Then you want send the output of grep to a while loop to process it. 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 . 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

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.

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 \;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM