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'
grep is very often used as a "filter" with other commands. It allows you to filter out useless information from the output of commands. To use grep as a filter, you must pipe the output of the command through grep . The symbol for pipe is " | ".
The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.
If you want to "clean" the results you can filter them using pipe | for example: grep -n "test" * | grep -v "mytest" > output-file will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v ) - and will redirect the result to an output file.
You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.
grep -l -r "TWL" --exclude=*.csv* | xargs cp -t ~/data/lidar/tmp-ajp2/
Explanation:
-l
option to output file names only-t
option to specify target directory (and avoid using placeholders)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With