需要awk脚本来解析ethernet statistics命令的输出
我已将命令输出为以下格式:需要awk脚本来解析ethernet statistics命令的输出,awk,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: --------------------
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中执行此操作。如何:
# 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的
,以及传输的数据包计数:
/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
谢谢-这非常有帮助。如果我想为ent0或ent1使用一个变量,它的语法是什么?我尝试执行adapter=“ent0”,然后用$adapter替换脚本中的ent0,但这似乎不起作用。