How to pipe output from grep to cp?

This worked for me when searching for files with a specific date:

 ls | grep '2018-08-22' | xargs -I '{}' cp '{}' ~/data/lidar/tmp-ajp2/

To copy files to grep found directories, use -printf to output directories and -i to place the command argument from xarg (after pipe)

find ./ -name 'filename.*' -print '%h\n' | xargs -i cp copyFile.txt {}

this copies copyFile.txt to all directories (in ./) containing "filename"


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)

you need xargs with the placeholder option:

grep -r "TWL" --exclude=*.csv* | xargs -I '{}' cp '{}' ~/data/lidar/tmp-ajp2/

normally if you use xargs, it will put the output after the command, with the placeholder ('{}' in this case), you can choose the location where it is inserted, even multiple times.

Tags:

Linux

Shell

Grep

Cp