How to pipe output from grep to cp?

58,641

Solution 1

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)

Solution 2

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.

Solution 3

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

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

Solution 4

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"

Share:
58,641
Borealis
Author by

Borealis

Updated on July 09, 2022

Comments

  • Borealis
    Borealis almost 2 years

    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'

  • marcelocra
    marcelocra over 7 years
    The -l option does not work for me. Aside from that, it works fine.
  • MeadowMuffins
    MeadowMuffins about 7 years
    -t is said an illegal option for cp on macOS sierra.
  • mrun
    mrun almost 7 years
    Would you care to elaborate on that?
  • recursion
    recursion almost 6 years
    please explain xargs -I '{}' cp '{}' ~/data/lidar/tmp-ajp2/
  • MAbraham1
    MAbraham1 almost 6 years
    @santosh-kumar, the '{}' are placeholders for the results of the grep listing ls | grep. So in my case, the command listed all the files that match the given date in their filename, and then copied each file to a specific directory.
  • Richard Tyler Miles
    Richard Tyler Miles over 4 years
    I still had issues with cp using this syntax. Chris Maes solution below worked for me
  • Stringers
    Stringers about 4 years
    Had issues with this answer where the filenames contained spaces.
  • aVeRTRAC
    aVeRTRAC over 3 years
    Is there a way to use this solution if the file name length is too long for cp?