【问题标题】:search for multiple words in file在文件中搜索多个单词
【发布时间】:2011-05-18 21:30:50
【问题描述】:

如果我希望使用 grep 在文件中搜索单词的出现,我会使用

grep token file

如果我想搜索包含多个标记的行,伪代码:

grep "token1 and token2" file

如何做到这一点?

【问题讨论】:

    标签: linux search grep


    【解决方案1】:

    想到的最简单的事情是

    grep token1 file | grep -h token2
    

    如果您想以特定顺序匹配模式,请考虑正则表达式:

    grep -E 'token1(.*?)token2' file
    

    要匹配 token1token2(在任何行),我会这样做

    grep -e token1 -e token2 *.cpp
    

    只列出匹配文件的文件名,而不是特定的匹配行:

    grep -l -e token1 -e token2 *.cpp
    

    【讨论】:

    • 第二个 grep 在第一个 grep 的输出中搜索,而不是在初始文件中
    • 我看不出区别
    • 如果你有一个带有 token1 的行和第二行带有 token2 这个 grep 将不会显示任何你需要使用这样的东西: grep -e token1 -e token2
    • @Ovi-WanKenobi 这正是问题所在
    • @Ovi-WanKenobi 我详细阐述了我的答案以使事情更加明确
    【解决方案2】:

    Grep 没有 AND 运算符,您可以使用 awk 代替:

    awk '/token1/ && /token2/' file
    

    【讨论】:

      【解决方案3】:

      试试这个:

      grep token1 file | grep token2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-13
        相关资源
        最近更新 更多