extract average time from ping -c

别等时光非礼了梦想. 提交于 2019-12-21 07:14:11

问题


I want to extract from the command ping -c 4 www.stackoverflow.com | tail -1| awk '{print $4}' the average time.

107.921/108.929/110.394/0.905 ms

Output should be: 108.929


回答1:


One way is to just add a cut to what you have there.

ping -c 4 www.stackoverflow.com | tail -1| awk '{print $4}' | cut -d '/' -f 2



回答2:


ping -c 4 www.stackoverflow.com | tail -1| awk -F '/' '{print $5}' would work fine.

"-F" option is used to specify the field separator.




回答3:


This might work for you:

ping -c 4 www.stackoverflow.com | sed '$!d;s|.*/\([0-9.]*\)/.*|\1|'



回答4:


The following solution uses Bash only (requires Bash 3):

[[ $(ping -q -c 4 www.example.com) =~ \ =\ [^/]*/([0-9]+\.[0-9]+).*ms ]] \
&& echo ${BASH_REMATCH[1]}

For the regular expression it's easier to read (and handle) if it is stored in a variable:

regex='= [^/]*/([0-9]+\.[0-9]+).*ms'
[[ $(ping -q -c 4 www.example.com) =~ $regex ]] && echo ${BASH_REMATCH[1]}



回答5:


Promoting luissquall's very elegent comment to an answer:

 ping -c 4 www.stackoverflow.com | awk -F '/' 'END {print $5}'



回答6:


Direct extract mean time from ping command:

ping -w 4 -q www.duckduckgo.com  | cut -d "/" -s -f5

Options:

-w time out 4 seconds
-q quite mode
-d delimiter 
-s skip line without delimiter
-f No. of field - depends on your system - sometimes 5th, sometimes 4th

I personly use is this way:

if [ $(ping -w 2 -q www.duckduckgo.com | cut -d "/" -s -f4 | cut -d "." -f1) -lt 20 ]; then
 echo "good response time"
else 
 echo "bad response time"
fi


来源:https://stackoverflow.com/questions/9634915/extract-average-time-from-ping-c

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