2017-02-23 40 views
1

我想ping一个destination_ip并将连续数据包丢失的计数重定向到ping_result.txt文件。 假设平的结果是这样的:bash脚本统计连续数据包丢失

reply from destination_ip 
request timed out 
request timed out 
reply from destination_ip 
request timed out 
request timed out 
request timed out 
request timed out 
reply from destination_ip 

输出应该是这样的:

0 
1 
2 
0 
1 
2 
3 
4 
0 
+1

未来,很高兴看到您尝试的代码,而不是让某人为您做功课。 –

回答

3

在AWK:

... | awk '/reply/{count = 0} {print count++}' > ping_result.txt 

本质:

  • 重置count如果收到答复。
  • 打印count并增加它。
+0

谢谢muru美丽的意见和使用awk – aschkant

2

甚至还没有接近美如muru's答案,但有人谁是用awk这是我会做什么风化相当不:

这是只要你有计算连续丢包输出保存在一个文件 - output.txt

COUNT=0 
while read line; do 
    if [[ $line == "reply"* ]] 
     then ((COUNT=0)) 
    else ((COUNT++)) 
    fi 
    echo $COUNT 
done <output.txt> ping_result.txt 

因此,它遍历整个文件,找到任何以回复开头并将计数设置为0的行,否则将递增。

我刚刚通读了Why is using a shell loop to process text considered bad practice?。所以这可能不是最好的主意。

+0

谢谢FUBAR。其实我期待着这样的编程。 但Muru的建议是一个很好的捷径;) – aschkant