我从命令输出的格式如下:
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 :(得分: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
的{{1}}选项传入变量:
awk