filter ping result with grep and awk altogether doesn't work

落爺英雄遲暮 提交于 2020-07-22 05:40:49

问题


I want to pipe the ping output with only its delay time to a text. while I do , I get this as expected

ping somesite 
PING somesite  (220.181.57.217) 56(84) bytes of data.
64 bytes from 220.181.57.217: icmp_seq=1 ttl=52 time=43.4 ms
64 bytes from 220.181.57.217: icmp_seq=2 ttl=52 time=43.7 ms
64 bytes from 220.181.57.217: icmp_seq=3 ttl=52 time=43.4 ms

Then I do this

ping somesite | awk -F '[:=]'  '{print $5}'

43.3 ms
43.2 ms
43.3 ms
43.2 ms
43.2 ms
43.1 ms
43.1 ms
43.3 ms
43.2 ms
43.6 ms
43.3 ms
43.3 ms

So The first line is blank, then I figured I had to get rid of it first.

ping somesite | grep -v "PING" | awk -F '[:=]'  '{print $5}'

But there isn't any output. When I do either

ping somesite | grep -v "PING"

or

 ping somesite | awk -F '[:=]'  '{print $5}'

It will work. When putting them together. It won't. I'd like to know the reason for this.


回答1:


You're not getting any output when piping with grep due to block buffering in grep command.

You can make grep use the line buffering so get the output for each line:

ping google.com | grep --line-buffered -v "PING" | awk -F '[:=]' '{print $5}'

However you don't need grep because you can do this using single awk:

ping google.com | awk -F '[:=]' 'NR>1{print $5}'



回答2:


With a small modification:

ping somesite | awk -F '[:=]'  'NR!=1 {print $5}'



回答3:


I've figured it out by the answer from https://askubuntu.com/questions/562344/what-does-grep-line-buffering-do

So pretty much grep buffers the output until 4096 bytes before sending the lines to awk. The grep option --line-buffered will solve my problem.




回答4:


Checking with NR (Number of records)actually remove first record from the output,

ping somesite | awk -F '[:=]'  'NR!=1 {print $5}'

or

ping somesite | awk -F '[:=]'  'NR>1 {print $5}'

You can check with NF (Number of fields) to filter any such record which doesn't fit in pattern,

ping somesite | awk -F '[:=]'  'NF==5 {print $5}'


来源:https://stackoverflow.com/questions/41162250/filter-ping-result-with-grep-and-awk-altogether-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!