Shell-Script

在單個命令中使用兩個分隔符從 awk 獲取結果

  • April 6, 2022

僅 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”中擷取整數 4。

ping -c 4 8.8.8.8 | awk -F ',' '/received/ { print $2 }'

結果是 4 received。我只想從上面的命令中擷取數字 4。我怎樣才能做到這一點?分隔符現在是空格。

所有你需要的是:

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 fileping -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>

引用自:https://unix.stackexchange.com/questions/697944