Friday, May 17, 2024
7
rated 0 times [  7] [ 0]  / answers: 1 / hits: 1720  / 2 Years ago, sat, september 10, 2022, 2:41:29

I need help to extract only the time's value when pinging using sed.



ping 192.168.1.1
PING 192.168.1.11 (192.168.1.11) 56(84) bytes of data.
64 bytes from 192.168.1.11: icmp_seq=1 ttl=64 time=0.028 ms
64 bytes from 192.168.1.11: icmp_seq=2 ttl=64 time=0.027 ms
64 bytes from 192.168.1.11: icmp_seq=3 ttl=64 time=0.024 ms
64 bytes from 192.168.1.11: icmp_seq=4 ttl=64 time=0.031 ms


So after using sed I would like to get the following output:



ping 192.168.1.1 | sed '???'
0.028
0.027
0.024
0.031


Thank you!


More From » command-line

 Answers
6

With sed you can do:



ping 192.168.1.1 | sed -n 's/.*time=([^ ]*).*/1/p'


That simply looks for the longest stretch of non-space after time=, uses parentheses to capture it so we can later refer to it as 1 and just replaces everything on the line with whatever was captured. The -n (don't print by default) along with the /p (print if this worked) at the end of the substitution operator ensure we only print relevant lines.



I wouldn't use sed for this though, other tools are simpler here. For example:




  1. grep



    ping 192.168.1.1 | grep -Po 'time=KS+'

  2. Perl



    ping 192.168.1.1 | perl -lne '/time=(S+)/ && print $1'

  3. awk



    ping 192.168.1.1 | awk -F'[= ]' '/time=/{print $(NF-1)}'


[#10699] Sunday, September 11, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
errettas

Total Points: 160
Total Questions: 118
Total Answers: 91

Location: Laos
Member since Fri, Sep 11, 2020
4 Years ago
;