Linux

使用 sed 或 awk 從文件中提取欄位

  • October 25, 2018

我有 bash 腳本來收集所有硬體資訊,但缺少以下記憶體資訊,所以這就是我想要做的。

以下命令為您提供DIMM記憶體模組的狀態,

[root@Linux ~]# hpasmcli -s 'show dimm'

DIMM Configuration
------------------
Processor #:                     1
Module #:                     1
Present:                      Yes
Form Factor:                  9h
Memory Type:                  DDR3(18h)
Size:                         8192 MB
Speed:                        1333 MHz
Supports Lock Step:           No
Configured for Lock Step:     No
Status:                       Ok

Processor #:                     1
Module #:                     12
Present:                      Yes
Form Factor:                  9h
Memory Type:                  DDR3(18h)
Size:                         8192 MB
Speed:                        1333 MHz
Supports Lock Step:           No
Configured for Lock Step:     No
Status:                       Ok

Processor #:                     2
Module #:                     1
Present:                      Yes
Form Factor:                  9h
Memory Type:                  DDR3(18h)
Size:                         8192 MB
Speed:                        1333 MHz
Supports Lock Step:           No
Configured for Lock Step:     No
Status:                       Ok

Processor #:                     2
Module #:                     12
Present:                      Yes
Form Factor:                  9h
Memory Type:                  DDR3(18h)
Size:                         8192 MB
Speed:                        1333 MHz
Supports Lock Step:           No
Configured for Lock Step:     No
Status:                       DIMM is degraded

想要在單行中提取Size:和需要它,如下所示Status:

最終輸出將如下所示。我可以使用其他語言,如 python 或 perl,但我用 bash 編寫,所以我需要 bash 中的一些東西,我可以做多個for loop並使用變數來使其工作,但我需要一些簡單或簡單的東西,比如sed/awk. 我怎樣才能在 sed/awk 中實現這一點?

8192MB - Ok
8192MB - OK
8192MB - OK 
8192MB - DIMM is degraded

一個不grep | awk | sed | awk使用,而是只使用一個的解決方案awk

hpasmcli -s 'show dimm' | awk 'BEGIN { stick=0 } $1 == "Size:" { dimm[++stick] = $2" "$3} $1 == "Status:" { $1=""; status[stick]=$0 }  END {for( i in dimm ) { print dimm[i], "-", status[i] } }'
8192 MB - Ok
8192 MB - Ok
8192 MB - Ok
8192 MB - DIMM is degraded

awk腳本,為了可讀性而重新格式化:

BEGIN { 
 stick=0 
} 
$1 == "Size:" { 
 dimm[++stick] = $2" "$3
} 
$1 == "Status:" { 
 $1="" 
 status[stick]=$0
}  
END {
 for( i in dimm ) { 
   print dimm[i], "-", status[i] 
 } 
}'

引用自:https://unix.stackexchange.com/questions/477793