问题
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'
回答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)
回答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.
回答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/
回答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"
回答5:
grep -rl '/directory/' -e 'pattern' | xargs cp -t /directory
来源:https://stackoverflow.com/questions/33140583/how-to-pipe-output-from-grep-to-cp