【问题标题】:Using Grep with Xargs and Process Substitution将 Grep 与 Xargs 和进程替换一起使用
【发布时间】:2018-07-30 02:42:44
【问题描述】:

我正在尝试通过 xargs 传递 grep 查询,同时通过进程替换传递文件。

command1 | xargs -I{} grep {} <(command2)

制作虚拟文件

for f in {1..50}; do echo $f >> test50.txt; done

for f in {25..30}; do echo $f >> test5.txt; done

xargs 和 grep 的进程替换

cat test5.txt | xargs -I{} grep {} <(cat test50.txt)

输出是:

25

想要的输出是:

25
26
27
28
29
30

我认为问题在于 grep 如何接收输入文件,它在一行后停止,而我希望它搜索整个输入文件

【问题讨论】:

    标签: grep pipe stdin xargs process-substitution


    【解决方案1】:

    考虑一下

    cat test5.txt | xargs -I{} echo {} &lt;(cat test50.txt)

    产生

    25 /dev/fd/63
    26 /dev/fd/63
    27 /dev/fd/63
    28 /dev/fd/63
    29 /dev/fd/63
    30 /dev/fd/63
    

    因此

    cat test5.txt | xargs -I{} cat {} &lt;(cat test50.txt)

    输出

    cat: 25: No such file or directory
    1
    2
    --cutted for brevity--
    49
    50
    cat: 26: No such file or directory
    cat: 27: No such file or directory
    cat: 28: No such file or directory
    cat: 29: No such file or directory
    cat: 30: No such file or directory
    

    您的问题不是关于grep,而是关于bash 中的process substitution。进程替换创建一个命名管道。接下来,来自该管道的所有数据都在 first 调用提供给xargs 的命令中使用(在您的示例中它是grep,在我上面的echocat 中),所以以25 作为第一个参数的那个。

    这会起作用

    cat test5.txt | xargs -I{} bash -c " grep {} &lt;(cat test50.txt)"

    因为它为每个 grep 独立调用创建“新鲜”process substitution

    【讨论】:

      【解决方案2】:

      使用 GNU Parallel,它看起来像这样:

      cat test5.txt | parallel 'grep {} <(cat test50.txt)'
      

      【讨论】:

        【解决方案3】:

        不需要xargs,因为grep 已经有办法从文件中指定搜索词

        $ seq 50 > f1
        $ seq 25 30 > f2
        $ grep -Fxf f2 f1
        25
        26
        27
        28
        29
        30
        

        来自man grep

        -F, --fixed-strings 将 PATTERN 解释为固定字符串列表(而不是正则表达式),由换行符分隔, 任何一个都将被匹配。

        -x, --line-regexp 仅选择与整行完全匹配的匹配项。对于正则表达式模式,这是 就像给模式加上括号,然后用 ^ 和 $ 包围它。

        -f 文件,--file=文件 从 FILE 中获取模式,每行一个。如果此选项被多次使用或与 -e (--regexp) 选项结合使用,则搜索所有给定的模式。空文件包含零个模式,因此不匹配任何内容。

        【讨论】:

          猜你喜欢
          • 2014-09-24
          • 2021-04-18
          • 1970-01-01
          • 1970-01-01
          • 2012-11-10
          • 1970-01-01
          • 1970-01-01
          • 2016-12-27
          • 2019-04-12
          相关资源
          最近更新 更多