How to pipe output from grep to cp?

Borealis picture Borealis · Oct 15, 2015 · Viewed 49.1k times · Source

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'

Answer

kostya picture kostya · Oct 15, 2015
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)