仅 ping 命令的输出:
[root@servera ~]# ping -c 4 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=8.04 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=128 time=7.47 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=128 time=7.72 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=128 time=7.50 ms
--- 8.8.8.8 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3007ms
rtt min/avg/max/mdev = 7.473/7.683/8.037/0.225 ms
我只想从“4 returned”中捕获整数4。
ping -c 4 8.8.8.8 | awk -F ',' '/received/ { print $2 }'
结果是4 received
。我只想捕获上述命令中的数字 4。我怎样才能做到这一点?现在分隔符是空格。
答案1
所有你需要的是:
awk '/received/{print $4}'
例如,用于获取与问题中cat file
相同的输入:awk
$ cat file
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=8.04 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=128 time=7.47 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=128 time=7.72 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=128 time=7.50 ms
--- 8.8.8.8 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3007ms
rtt min/avg/max/mdev = 7.473/7.683/8.037/0.225 ms
$ cat file | awk '/received/{print $4}'
4
显然只需替换cat file
为ping -c 4 8.8.8.8
您的实际测试即可。
回应下面的 OP 评论,询问它匹配哪一行:
$ awk '/received/' file
4 packets transmitted, 4 received, 0% packet loss, time 3007ms
以及为什么要打印字段 4:
$ awk '/received/{for (i=1; i<=NF; i++) print i, "<" $i ">"}' file
1 <4>
2 <packets>
3 <transmitted,>
4 <4>
5 <received,>
6 <0%>
7 <packet>
8 <loss,>
9 <time>
10 <3007ms>
答案2
还有另一种方法可以做到这一点awk
(类似于对其中一个答案进行评论)
awk -F, '/received/ {print int($2)}'
函数int()
将“丢弃”第一个数字之后的非数字信息
答案3
您已经得到了一些很好的 awk 答案,所以这里有一些替代方案。
GNU
grep
$ ping -c 4 8.8.8.8 | grep -oP '\d+(?= received,)' 4
珀尔
$ ping -c 4 8.8.8.8 | perl -lne 'print $1 if /(\d+) received,/' 4
sed
$ ping -c 4 8.8.8.8 | sed -En 's/.*, ([0-9]+) received,.*/\1/p' 4
答案4
ping -c4 <ipadress>|awk '/received/{for(i=1;i<=NF;i++){if($i ~ /received/){print $(i-1)}}}'
输出
4