How to pipe output from grep to cp?
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"
Borealis
Updated on July 09, 2022Comments
-
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 thegrep
command and pipe it into acp
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 over 7 yearsThe
-l
option does not work for me. Aside from that, it works fine. -
MeadowMuffins about 7 years
-t
is said an illegal option forcp
on macOS sierra. -
mrun almost 7 yearsWould you care to elaborate on that?
-
recursion almost 6 yearsplease explain xargs -I '{}' cp '{}' ~/data/lidar/tmp-ajp2/
-
MAbraham1 almost 6 years@santosh-kumar, the
'{}'
are placeholders for the results of the grep listingls | 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 over 4 yearsI still had issues with cp using this syntax. Chris Maes solution below worked for me
-
Stringers about 4 yearsHad issues with this answer where the filenames contained spaces.
-
aVeRTRAC over 3 yearsIs there a way to use this solution if the file name length is too long for cp?