如果匹配则 awk 打印 2 行

如果匹配则 awk 打印 2 行

我的一些输出如下所示:

Gathering data for drive 1 ...
Drive name:  id1,sd@n5000cca17096
Drive Model: HUH721010AL4204
Drive Speed: 7200 RPMs
Drive Temp:  41 C

Gathering data for drive 2 ...
Drive name:  id1,sd@n5000cca24156
Drive Model: HUH721010AL4204
Drive Speed: 7200 RPMs
Drive Temp:  41 C

Gathering data for drive 3 ...
Drive name:  id1,sd@n5000cca8749
Drive Model: HUH721010AL4204
failed to get drive stats

Gathering data for drive 4 ...
Drive name:  id1,sd@n5000cca19183
Drive Model: HUH721010AL4204
Drive Speed: 7200 RPMs
Drive Temp:  41 C

Gathering data for drive 5 ...
Drive name:  id1,sd@n5000cca4607
Drive Model: HUSMH8010BSS204
failed to get drive stats

Gathering data for drive 6 ...
Drive name:  id1,sd@n5000cca10152
Drive Model: HUH721010AL4204
Drive Speed: 7200 RPMs
Drive Temp:  41 C

我想打印无法返回驱动器统计信息的任何驱动器的“驱动器名称”(因此匹配failed to get drive stats)。

我知道如何获取上一行:

awk '$0=="failed to get drive stats" && $2>1 {print f} {f=$0}'

但这对我没有帮助。

期望的输出:

Drive name:  id1,sd@n5000cca8749
Drive name:  id1,sd@n5000cca4607

编辑:

由于某种原因,当输出被重定向时,它的显示方式与终端上的显示方式不同。如果我运行:

command >out.txt 2>&1

输出文件将如下所示:

failed to get drive stats
failed to get drive stats

Gathering data for drive 1 ...
Drive name:  id1,sd@n5000cca17096
Drive Model: HUH721010AL4204
Drive Speed: 7200 RPMs
Drive Temp:  41 C

Gathering data for drive 2 ...
Drive name:  id1,sd@n5000cca24156
Drive Model: HUH721010AL4204
Drive Speed: 7200 RPMs
Drive Temp:  41 C

....

两个 awk 答案都提供了工作,但我猜我还有其他问题

答案1

$ awk -F ':' '$1 == "Drive name" { saved = $0 } $0 == "failed to get drive stats" { print saved }' file
Drive name:  id1,sd@n5000cca8749
Drive name:  id1,sd@n5000cca4607

这首先将输入字段分隔符设置为:。然后saved,只要找到指定驱动器名称的行,它就会将该行保存在变量中。

如果一行显示,则打印failed to get drive stats的当前值。saved

答案2

这就是为什么 awk 有“段落模式”,你所需要的只是:

$ awk -v RS= -F'\n' '/failed to get drive stats/{print $2}' file
Drive name:  id1,sd@n5000cca8749
Drive name:  id1,sd@n5000cca4607

答案3

尝试使用下面的方法,效果很好

awk '{a[++i]=$0}/failed/{for(x=NR-2;x<NR;x++)print a[x]}' filename| sed -n '1~2p'

输出

Drive name:  id1,sd@n5000cca8749
Drive name:  id1,sd@n5000cca4607

相关内容