【问题标题】:Using grep to search for multiple keywords on different lines使用 grep 搜索不同行的多个关键字
【发布时间】:2019-03-08 13:08:56
【问题描述】:

我正在完成一个涉及解决谋杀之谜的命令行游戏/挑战。

其中一个步骤是通过使用grep在一个文件中搜索多个关键字来搜索嫌疑人。

但是,该文件包含数千行具有以下格式的文本:

License Plate: L337ZR9
Make: Honda
Color: Red
Owner: Katie Park
Height: 6'2"

我曾尝试通过以下方式使用 grep:

cat vehicles | grep -i 'L337' | grep -i 'honda'
ls | grep -i 'honda\|blue\|L337'

但据我了解,这些命令将为我提供与我的三个搜索词中的任何一个匹配的任何结果。

我需要什么命令来搜索车辆文件并显示匹配只匹配具有 L337 车牌的蓝色本田 - 换句话说,什么命令允许 grep 查找并显示多个匹配搜索词的结果?

【问题讨论】:

    标签: bash command-line grep pipe file-search


    【解决方案1】:

    使用 GNU grep.

    示例

    来源

    License Plate: L337ZR9
    Make: Honda
    Color: Blue
    Owner: Katie Park
    Height: 6'2"
    License Plate: L338ZR9
    Make: Honda
    Color: Black
    Owner: James Park
    Height: 6'0"
    

    命令

    grep -Pzo '\w+:\s*L337ZR9\n\w+:\s+Honda\n\w+:\s*Blue' file
    

    结果

    Plate: L337ZR9
    Make: Honda
    Color: Blue
    

    说明

    来自grep男人:

       -z, --null-data
              Treat the input as a set of lines,
    

    注意grep (GNU grep) 2.20已测试

    【讨论】:

      【解决方案2】:

      首先意识到你是grepping 记录,而不是行。

      所以将 5 行记录合并为一行:

      cat licenseplates | paste - - - - -
      

      现在突然轻松grep

      cat licenseplates | paste - - - - - |
        grep -i 'L337' | grep -i 'honda' | grep -i blue
      

      最后你需要将匹配的行折回5行记录:

      cat licenseplates | paste - - - - - |
        grep -i 'L337' | grep -i 'honda' | grep -i blue |
        sed 's/\t/\n/g'
      

      【讨论】:

        猜你喜欢
        • 2012-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-23
        相关资源
        最近更新 更多