Search code examples
linuxcommand-lineextractping

Extract only integer milliseconds from linux commandline ping


I try to extract just integer number of milliseconds from continuous ping output in OpenWRT commandline. Example from ping 8.8.8.8

64 bytes from 8.8.8.8: seq=6 ttl=55 time=6.356 ms
64 bytes from 8.8.8.8: seq=7 ttl=55 time=6.520 ms
...

Desire output should looks like this:

6
6
...

Just integer (left part of number). Without fraction part and wihout dot.

I tried to cut output using pipes, firstly cutting equal signs ping 8.8.8.8 | cut -d '=' -f 4 which works

6.389 ms
6.051 ms
...

Then cutting also dots to get integer only ping 8.8.8.8 | cut -d "=" -f4 | cut -d '.' -f1 but then no output shows at all. I tried also using awk but when I use more than one pipe with those commands, there is no output. Could you show me how to do that.


Solution

  • You can pipe the output through perl (for example) and use a simple regex:

    ping -c3 8.8.8.8 | perl -nle '/time=(\d+)/ && print $1'
    

    This will print the integer part.

    You could also round the milliseconds to the nearest integer with printf

    ping -c3 8.8.8.8 | perl -ne '/time=([\d\.]+) ms/ && printf "%.0f\n", $1'