我目前正在尝试编写一个bash脚本来记录atm的平均ping时间。三个不同的目标,每20秒一整天。 这就是我目前所拥有的......
#!/bin/bash
echo "SCRIPT STARTED" >> pingthing.log
date +%d.%m.%y' '%R:%S >> pingthing.log
for i in $(seq 1 4320);
do
date +%d.%m.%y' '%R:%S >> pingthing.log
#save just target IP and avg time.
ping -c 3 -q -W 2 8.8.8.8 >> pingthing.log
ping -c 3 -q -W 2 64.25.40.16 >> pingthing.log
ping -c 3 -q -W 2 96.17.199.48 >> pingthing.log
sleep 20
done
echo "SCRIPT ENDED" >> pingthing.log
date +%d.%m.%y' '%R:%S >> pingthing.log
现在我的问题......
这是目前我的日志文件中保存的内容..但这仅显示了它的开头
SCRIPT STARTED
07.02.14 22:14:13
07.02.14 22:14:13
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2000ms
rtt min/avg/max/mdev = 127.773/152.321/192.204/28.452 ms
PING 64.25.40.16 (64.25.40.16) 56(84) bytes of data.
--- 64.25.40.16 ping statistics ---
3 packets transmitted, 3 received, +2 duplicates, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 213.889/237.182/286.825/26.656 ms
PING 96.17.199.48 (96.17.199.48) 56(84) bytes of data.
--- 96.17.199.48 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 305.028/340.081/375.135/35.058 ms
现在我想要只有目标及其平均值。 ping命令的时间,如
SCRIPT STARTED
07.02.14 22:14:13
07.02.14 22:14:13
8.8.8.8 152.321
64.25.40.16 237.182
96.17.199.48 340.081
我知道我应该将ping命令传递给sed / awk,但由于我没有这方面的经验,我暂时将其删除了。
我不希望你只是解决所有事情,我来这里讨论和学习。 对于100%损失问题..输出看起来像这样
ping -W 2 -q -c 3 1.1.1.1
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
--- 1.1.1.1 ping statistics ---
3 packets transmitted, 0 received, 100% packet loss, time 2016ms
现在这里没有成功ping的汇总行,所以我不能将sed / awk用于该模式..
答案 0 :(得分:1)
鉴于您发布的样本输入文件:
$ awk -F'[ /]' 'NR~/^[123]$/; /^---/{ip=$2} /^rtt/{print ip, $8}' file
SCRIPT STARTED
07.02.14 22:14:13
07.02.14 22:14:13
8.8.8.8 152.321
64.25.40.16 237.182
96.17.199.48 340.081
你没有告诉我们你想要的“100%损失问题”的输出,所以我不知道你想要做什么。只是将它包含在您的样本输入和预期输出中,除非有一些特定的原因,到目前为止还不清楚。
如果您想要的只是打印出100%的损失,您可以将脚本调整为:
awk -F'[ /]' 'NR~/^[123]$/; /^---/{ip=$2} /^rtt/{print ip, $8} /100% packet loss/{print ip, "100% packet loss"}' file
可能性无穷无尽......只需告诉我们您需要输出的内容。
这里一次只有一行评论:
awk -F'[ /]' ' # use space and / as the field separator
NR~/^[123]$/; # if youre on input line 1, 2, or 3, print that line (the default action)
/^---/{ip=$2} # if the line starts with 3 dashes, save the 2nd field as the IP address
/^rtt/{print ip, $8} # if the line starts with rtt, print the saved IP address and the 8th field which is the averages
/100% packet loss/{print ip, 2000} # if the line contains the 100%... statement, print the IP address and a default value of 2000
' file