简体   繁体   English

如何将输出从 grep 管道传输到 cp?

[英]How to pipe output from grep to cp?

I have a working grep command that selects files meeting a certain condition.我有一个工作grep命令,可以选择满足特定条件的文件。 How can I take the selected files from the grep command and pipe it into a cp command?如何从grep命令中获取选定的文件并将其通过管道传输到cp命令中?

The following attempts have failed on the cp end: cp端以下尝试都失败了:

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:在“/home/ubuntu/data/lidar/tmp-ajp2/”之后缺少目标文件操作数,请尝试“cp --help”以获取更多信息。


cp `grep -r "TWL" --exclude=*.csv*` ~/data/lidar/tmp-ajp2/

cp: invalid option -- '7' cp: 无效选项 -- '7'

grep -l -r "TWL" --exclude=*.csv* | xargs cp -t ~/data/lidar/tmp-ajp2/

Explanation:解释:

  • grep -l option to output file names only grep -l选项仅输出文件名
  • xargs to convert file list from the standard input to command line arguments xargs 将文件列表从标准输入转换为命令行参数
  • cp -t option to specify target directory (and avoid using placeholders) cp -t选项指定目标目录(并避免使用占位符)

you need xargs with the placeholder option:您需要带有占位符选项的xargs

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.一般来说,如果你使用xargs ,它会把输出指令,与(占位符'{}'在这种情况下),你可以选择在那里插入的位置,甚至多次。

在搜索具有特定日期的文件时,这对我有用:

 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)要将文件复制到 grep 找到的目录,请使用 -printf 输出目录,并使用 -i 放置来自 xarg 的命令参数(管道后)

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

this copies copyFile.txt to all directories (in ./) containing "filename"这会将 copyFile.txt 复制到所有包含“文件名”的目录(在 ./ 中)

grep -rl '/directory/' -e 'pattern' | grep -rl '/目录/' -e '模式' | xargs cp -t /directory xargs cp -t /目录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM