【问题标题】:How do you write what you piped to grep into a file if only the grep matches如果只有 grep 匹配,您如何将通过管道传输到 grep 的内容写入文件
【发布时间】:2021-02-17 17:13:56
【问题描述】:

假设我运行以下命令

 echo "I love the west indies " | grep indies 

因为上面的 grep 评估为真,因为会有一个实际匹配我想写“我爱西印度群岛”到文件

说我跑

echo "i love the west  indies " | grep america

什么都没有写,因为这个 grep 命令什么都不返回。我如何在 bash 中做到这一点?

【问题讨论】:

    标签: linux bash unix command-line grep


    【解决方案1】:

    使用 bash 的正则表达式:

    $ [[ $(echo "I love the west indies ") =~ .*indies.* ]] && echo ${BASH_REMATCH[0]} > file
    

    当你cat file:

    I love the west indies
    

    【讨论】:

      【解决方案2】:

      awk可以做条件重定向:

      echo "I love the west indies " | awk '/indies/ { print $0 > "my_file" }'
      

      【讨论】:

        【解决方案3】:

        您可以使用command substitution 捕获输出并在写入文件之前测试结果:

        result=$(echo "I love the west indies" | grep indies)
        if [ -n "$result" ]
        then echo "$result" > output.file
        fi
        

        'echo to output' 行中 "$result" 周围的引号至关重要。

        您可能还注意到,如果您不向文件写入任何内容,则创建的只是一个空文件。并且不向预先存在的文件附加任何内容只会更改其时间戳。因此,您也许可以使用其中之一:

        echo "I love the west indies" | grep indies > output.file   # Zaps previous content
        echo "I love the west indies" | grep indies >> output.file  # Keeps previous content
        

        可选后跟:

        [ -s output.file ] || rm -f output.file
        

        如果输出文件为空,则删除它。如果您在脚本中多次提及文件名,则需要使用变量作为文件名来代替 output.file

        【讨论】:

        • 注意你也可以写if result=$(echo "..." | grep ...); then,grep返回的值会被if求值。
        • @WilliamPursell:谢谢——是的,你可以。我倾向于不在if 条件下使用这样的作业(我不记得我是否曾经有充分的理由不这样做,但如果我这样做的话,很可能是 30 年前的原因),但它会起作用。
        猜你喜欢
        • 2011-07-17
        • 2017-06-04
        • 2017-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-04
        • 2018-11-17
        相关资源
        最近更新 更多