【问题标题】:unix match multiple patterns return successunix匹配多个模式返回成功
【发布时间】:2014-01-27 23:10:03
【问题描述】:

有没有一种简单的方法可以在文件中搜索多个模式并仅在找到两个模式时才返回成功。

例如,如果我有一个文件:

itemA
itemB
itemC
itemD

我想打印所有同时包含“itemA”和“itemD”的txt文件的名称

类似:

find . -name "*.txt" | xargs -n 1 -I {} sh -c "grep 'itemA AND itemB' && echo {}"

【问题讨论】:

    标签: bash shell unix awk grep


    【解决方案1】:
    awk '/ItemA/{f1=1} /ItemB/{f2=1} END{ exit (f1 && f2 ? 0 : 1) }' file
    

    【讨论】:

      【解决方案2】:
      find . -name "*.txt" -exec grep -l 'itemA' {} + | xargs grep -l 'itemB'
      

      如果您想特别注意特殊字符,请将 -Z 添加到 grep 并将 -0 添加到 xargs。

      【讨论】:

      • +1 表示简洁。 OSX 用户:使用--null 而不是-Zgrep
      【解决方案3】:

      将你的伪代码翻译成真实的:

      find . -name "*.txt" | xargs -n 1 -I {} sh -c "grep -q itemA {} && grep -q itemD {} && echo {}"
      

      您可以通过使第二个grep 打印文件名来缩短此时间:

      find . -name "*.txt" | xargs -n 1 -I {} sh -c "grep -q itemA {} && grep -l itemD {}"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-30
        • 2023-03-30
        • 2011-10-20
        相关资源
        最近更新 更多