Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pipe output from grep to cp?

Tags:

linux

grep

shell

cp

I have a working grep command that selects files meeting a certain condition. How can I take the selected files from the grep command and pipe it into a cp command?

The following attempts have failed on the cp end:

grep -r "TWL" --exclude=*.csv* | cp ~/data/lidar/tmp-ajp2/ 

cp: missing destination file operand after ‘/home/ubuntu/data/lidar/tmp-ajp2/’ Try 'cp --help' for more information.


cp `grep -r "TWL" --exclude=*.csv*` ~/data/lidar/tmp-ajp2/ 

cp: invalid option -- '7'

like image 912
Borealis Avatar asked Oct 15 '15 05:10

Borealis


People also ask

How do you pipe a grep output?

grep is very often used as a "filter" with other commands. It allows you to filter out useless information from the output of commands. To use grep as a filter, you must pipe the output of the command through grep . The symbol for pipe is " | ".

How do I print grep output?

The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.

How do I write grep output to a file?

If you want to "clean" the results you can filter them using pipe | for example: grep -n "test" * | grep -v "mytest" > output-file will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v ) - and will redirect the result to an output file.

How do I print multiple lines in grep?

You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.


1 Answers

grep -l -r "TWL" --exclude=*.csv* | xargs cp -t ~/data/lidar/tmp-ajp2/ 

Explanation:

  • grep -l option to output file names only
  • xargs to convert file list from the standard input to command line arguments
  • cp -t option to specify target directory (and avoid using placeholders)
like image 71
kostya Avatar answered Oct 02 '22 08:10

kostya