在匹配后搜索字符串

在匹配后搜索字符串

有没有办法在给定的匹配后搜索字符串?

例如,如果我运行dmidecode,它会提供很多信息。例如

BIOS Information
    Vendor: ABCD
    Version: 123456(V1.01)
    Release Date: 01/01/1970
    Address: 0xE0000
    Runtime Size: 128 kB
    ROM Size: 8192 kB
    Characteristics:
        PCI is supported
        BIOS is upgradeable
        BIOS shadowing is allowed
        Boot from CD is supported
        Selectable boot is supported
        BIOS ROM is socketed
        EDD is supported
        Japanese floppy for NEC 9800 1.2 MB is supported (int 13h)
        Japanese floppy for Toshiba 1.2 MB is supported (int 13h)
        5.25"/360 kB floppy services are supported (int 13h)
        5.25"/1.2 MB floppy services are supported (int 13h)
        3.5"/720 kB floppy services are supported (int 13h)
        3.5"/2.88 MB floppy services are supported (int 13h)
        8042 keyboard services are supported (int 9h)
        CGA/mono video services are supported (int 10h)
        ACPI is supported
        USB legacy is supported
        Targeted content distribution is supported
        UEFI is supported
    BIOS Revision: 1.21
    Firmware Revision: 1.21

现在,如果我 grep“version”,那么它将从dmidecode输出中获取各种匹配项。相反,有没有什么方法可以在 ^BIOS 单词之后搜索“版本”行并在第一个匹配处停止?所以输出将是这样的:

Version: 123456(V1.01)

答案1

$ sudo dmidecode |
    awk '/^BIOS/ { ++Bios } Bios && /Version/ { print; exit; }'
    Version: 02PI.M505.20110824.LEO
$ 

我们只是计算 BIOS 过去了,并在版本行上触发。

由于 BIOS 是第一个块(在我的系统上),并且 grep 有一个 max-count 选项,因此这也应该有效

sudo dmidecode | grep -m 1 'Version'

答案2

在很多情况下,您可以grep -A在第一次匹配后输出一些行,然后重新 grep 该结果

dmidecode | grep -A 3 "BIOS Information" | grep "Version"

相关内容