[英]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.