在 Bash/Shell 脚本中使用正则表达式搜索特定字符串

Searching for a particular string using Regex in Bash/Shell Scripting

我正在尝试为像 google 这样的网站回显 4 个 ICMP echo/echo 依赖数据包的平均往返时间(以毫秒为单位)。这是我目前的代码。

echo "$(ping -c 4 google.com | grep '??????')"

Ping 网站有效,但我不知道如何仅回显平均往返时间。我只使用 Regex 对 Web 表单进行验证,但我已经有一段时间没有使用它了。我假设我可以使用 Regex 来仅查找我正在搜索的内容,但如果有更好的方法来执行此操作,那也很棒。我正在使用 shell 为 linux ubuntu

编写脚本

这是输出示例。我唯一需要的部分是底部显示 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 输出如下所示:

$ 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(毫秒)

一个awk解法:

awk '/avg/ {split([=11=],arr,"/"); print arr[5]}'

其中:

  • /avg/ - 查找包含字符串 avg
  • 的行
  • split([=19=],arr,"/") - 使用正斜杠 (/) 作为分隔符拆分行,将段放在 arr[] 数组
  • print arr[5] - 打印 arr[] 数组的第 5 个元素

结合 ping:

ping -c 4 google.com | awk '/avg/ {split([=12=],arr,"/"); print arr[5]}'
66.467

并且如果我们需要包括时间的测量(在本例中为ms),我们还可以打印包含字符串avg的行的最后一个字段,例如:

ping -c 4 google.com | awk '/avg/ {split([=13=],arr,"/"); print arr[5],$NF}'
66.467 ms

注释:

  • OP 可能需要调整 awk 命令,如果他们的 ping 输出格式不同
  • 显然 (?) 每次 ping 运行 我们可能会得到一个略有不同的值。
  • 如果 OP 想要 100% 确定该值,则 ping 命令输出应保存到文件(或变量),然后 运行 awk 命令反对所述文件(或变量)