1

The output of a typical ping command is -

--- 192.168.1.107 ping statistics ---
2 packets transmitted, 1 received, 50% packet loss, time 1008ms
rtt min/avg/max/mdev = 0.288/0.288/0.288/0.000 ms

I want to display only "50% packet loss" portion on a terminal window when I run the ping command in a shell script. How should I proceed for it ?

1
  • 2
    ping -c 2 -q remotehost | sed -n 's/.*received, \([0-9]*%[^,]*\).*/\1/p' will work but subject to the format of the ping output.
    – alvits
    Jun 18, 2015 at 22:55

2 Answers 2

1

Using grep

-o tells grep to print only the matching portion:

ping -c2 -q targethost | grep -o '[^ ]\+% packet loss'

Using awk

If the output of ping is viewed as comma-separated fields, then, as shown in your sample output, the packet loss info is in the third field. This allows us to use awk as follows:

ping -c2 -q targethost | awk -F, '/packet loss/{print $3;}'
1

Using grep:

ping -c10 -f -q localhost | grep -E -o '[^[:space:]]+ packet loss'

Using awk:

ping -c10 -f -q localhost | awk -F', ' '/packet loss/ { print $3 }'

grep -o isn't posix, while the awk solution depends on the output format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.