Text-Processing
如果匹配,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
我想為無法返回驅動器統計資訊的任何驅動器列印“驅動器名稱”(因此匹配 on
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 答案都提供了工作,但我猜我還有其他問題
$ 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
這首先將輸入欄位分隔符設置為 a
:
。saved
然後,只要找到指定驅動器名稱的行,它就會將該行保存在變數中。如果一行顯示 ,則列印
failed to get drive stats
的目前值。saved
這就是 awk 具有“段落模式”的原因,您所需要的只是:
$ awk -v RS= -F'\n' '/failed to get drive stats/{print $2}' file Drive name: id1,sd@n5000cca8749 Drive name: id1,sd@n5000cca4607