简体   繁体   English

如何将排序结果通过管道传递给grep?

[英]How to pipe sorted results to grep?

$ grep HxH 20170213.csv | awk -F',' '{print $13}' | cut -b 25-27 | sort -u
868
881
896
904
913
914
918
919
920

Question> How to pipe the sorted results and feed into grep ? 问题>如何通过管道将排序后的结果输入grep

Now I have to do the following command manually. 现在,我必须手动执行以下命令。

grep 868 /tmp/aaa/*.csv
grep 881 /tmp/aaa/*.csv
...
grep 920 /tmp/aaa/*.csv

Since your output is numeric (output lines do not contain spaces), you can use a for loop with command substitution: 由于您的输出是数字(输出行不包含空格),因此可以使用带命令替换的for循环:

for id in $(grep HxH 20170213.csv | awk -F',' '{print $13}' \
            | cut -b 25-27 | sort -u); do
    grep $id /tmp/aaa/*.csv
done

Another option is to use xargs : 另一种选择是使用xargs

grep HxH 20170213.csv | awk -F',' '{print $13}' | cut -b 25-27 | sort -u \
    | xargs -n1 grep /tmp/aaa/*.csv -e

The xargs variant requires one to jump through a couple hoops to get right: xargs变体需要一个人跳几圈才能正确:

  • by default xargs would stick more than one pattern to the same grep , which is prevented using -n1 ; 缺省情况下, xargs会将多个模式粘贴到同一grep ,这可以使用-n1来防止;
  • xargs specifies the stdin contents as the last argument in the command line, which is a problem because grep expects pattern then file name. xargs将stdin内容指定为命令行中的最后一个参数,这是一个问题,因为grep模式,然后是文件名。 Fortunately, grep PATTERN FILES... can be spelled as grep FILES... -e PATTERN , which is why grep must be followed by -e . 幸运的是, grep PATTERN FILES...可以拼写为grep FILES... -e PATTERN ,这就是为什么grep后面必须带有-e

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

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