Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement