[英]Searching for a particular string using Regex in Bash/Shell Scripting
我正在尝试为 google 之类的网站回显 4 个 ICMP 回显/回显依赖数据包(以毫秒为单位)的平均往返时间。 这是我现在的代码。
echo "$(ping -c 4 google.com | grep '??????')"
ping 网站有效,但我不知道如何仅回显平均往返时间。 我只在 web forms 上使用 Regex 进行验证,但我有一段时间没有使用它。 我假设我可以使用 Regex 仅查找我正在搜索的内容,但如果有更好的方法来做到这一点,那也很棒。 我正在使用 shell 为 linux ubuntu 编写此脚本
这是 output 的示例。 我需要的唯一部分是底部的部分,上面写着rtt min/avg/max/mdev = 14.556/14.579/14.614/0.088 ms
。
PING google.com (142.250.74.238) 56(84) bytes of data.
64 bytes from par10s40-in-f14.1e100.net (142.250.74.238): icmp_seq=1 ttl=108 tim e=14.5 ms
64 bytes from par10s40-in-f14.1e100.net (142.250.74.238): icmp_seq=2 ttl=108 tim e=14.5 ms
64 bytes from par10s40-in-f14.1e100.net (142.250.74.238): icmp_seq=3 ttl=108 time=14.5 ms
64 bytes from par10s40-in-f14.1e100.net (142.250.74.238): icmp_seq=4 ttl=108 time=14.6 ms
--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3003ms
rtt min/avg/max/mdev = 14.556/14.579/14.614/0.088 ms
假设ping
output 如下所示:
$ ping -c 4 google.com
PING google.com (172.217.14.238): 56 data bytes
64 bytes from 172.217.14.238: icmp_seq=0 ttl=118 time=78.019 ms
64 bytes from 172.217.14.238: icmp_seq=1 ttl=118 time=62.416 ms
64 bytes from 172.217.14.238: icmp_seq=2 ttl=118 time=63.019 ms
64 bytes from 172.217.14.238: icmp_seq=3 ttl=118 time=62.415 ms
--- google.com ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max/stddev = 62.415/66.467/78.019/6.674 ms
在这种情况下,平均时间是66.467
(ms)
一种awk
解决方案:
awk '/avg/ {split($0,arr,"/"); print arr[5]}'
在哪里:
/avg/
- 查找字符串avg
的行split($0,arr,"/")
- 使用正斜杠 ( /
) 作为分隔符拆分行,将段放在arr[]
数组中print arr[5]
- 打印arr[]
数组的第 5 个元素结合ping
:
ping -c 4 google.com | awk '/avg/ {split($0,arr,"/"); print arr[5]}'
66.467
如果我们需要包括时间测量(在这种情况下是ms
),我们还可以打印包含字符串avg
的行的最后一个字段,例如:
ping -c 4 google.com | awk '/avg/ {split($0,arr,"/"); print arr[5],$NF}'
66.467 ms
注意事项:
ping
output 的格式不同,OP 可能需要调整awk
命令ping
命令 output 保存到文件(或变量)中,然后针对所述文件(或变量)运行awk
命令
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.