2013-02-04 58 views
1

我有以下格式從命令的輸出:需要awk腳本解析以太網統計數據的輸出命令

Ethernet STATISTICS (ent0) : 
Device Type: 2-Port 10/100/1000 Base-TX PCI-X Adapter (14108902) 
Hardware Address: 00:09:6b:6e:5d:50 
Transmit Statistics:       Receive Statistics: 
--------------------       ------------------- 
Packets: 0         Packets: 0 
Bytes: 0          Bytes: 0 
Interrupts: 0         Interrupts: 0 
Transmit Errors: 0       Receive Errors: 0 
Packets Dropped: 0  
ETHERNET STATISTICS (ent1) : 
Device Type: 2-Port 10/100/1000 Base-TX PCI-X Adapter (14108902) 
Hardware Address: 00:09:6b:6e:5d:50 
Transmit Statistics:       Receive Statistics: 
--------------------       ------------------- 
Packets: 30         Packets: 0 
Bytes: 1800         Bytes: 0 
Interrupts: 0         Interrupts: 0 
Transmit Errors: 0       Receive Errors: 0 
Packets Dropped: 0       Packets Dropped: 0 
               Bad Packets: 0 

我需要保存到變量傳遞與ENT0相關的數據包的數量和數據包的數量傳輸與ent1相關聯。我需要使用awk來執行此任務,並且我知道如何提取數據包數量,但我不知道如何將它與其上面幾行所列的適配器(ent0或ent1)相關聯。好像我需要使用某種嵌套循環,但不知道如何在awk中執行此操作。

回答

0

如何:

# list all ent's and there counts 
$ awk '/ent[0-9]+/{e=$3}/^Packets:/{print e,$2}' file 
(ent0) 0 
(ent1) 30 

# list only the count for a given ent 
$ awk '/ent0/{e=$3}/^Packets:/&&e{print $2;exit}' file 
0 

$ awk '/ent1/{e=$3}/^Packets:/&&e{print $2;exit}' file 
30 

說明:

第一個腳本打印所有ent's與數據包傳輸計數一起:

/ent[0-9]+/  # For lines that contain ent followed by a digit string 
{ 
    e=$3   # Store the 3rd field in variable e 
} 
/^Packets:/  # Lines that start with Packet: 
{ 
    print e,$2  # Print variable e followed by packet count (2nd field) 
} 

第二個腳本只打印了計數給出ent

/ent0/    # For lines that match ent0 
{ 
    e=$3   # Store the 3rd field 
} 
/^Packets:/&&e  # If line starts with Packets: and variable e set 
{ 
    print $2  # Print the packet count (2nd field) 
    exit   # Exit the script 
} 

您可以使用命令替換在bash存儲在shell變量的值:

$ entcount=$(awk '/ent1/{e=$3}/^Packets:/&&e{print $2;exit}' file) 

$ echo $entcount 
30 

awk-v選項來傳遞變量:

$ awk -v var=ent0 '$0~var{e=$3}/^Packets:/&&e{print $2;exit}' file 
0 

$ awk -v var=ent1 '$0~var{e=$3}/^Packets:/&&e{print $2;exit}' file 
30 
+0

謝謝你 - 這是非常很有幫助。 – user1905366

+0

如果我想爲ent0或ent1使用變量,那麼它的語法是什麼?我試圖做adapter =「ent0」,然後用$ adapter替換腳本中的ent0,但這似乎不起作用。 – user1905366