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

第二个脚本仅打印给定的计数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

以及传递变量的-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 回答