Search code examples
linuxshellgrepcp

How to pipe output from grep to 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'


Solution

  • 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)