1

次の形式でコマンドから出力しました。

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でこれを行う方法がわかりません。

4

1 に答える 1

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)
}

2番目のスクリプトは、指定されたカウントのみを出力します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でコマンド置換を使用して、シェル変数に値を格納できます。

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

$ echo $entcount 
30

そして、変数を渡す-vオプション:awk

$ 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
于 2013-02-04T20:42:52.013 に答える