Bash

如何使用 AWK 從不同的行列印不同的欄位

  • October 19, 2022
Here is my sample :
PING my.host.local (10.10.10.10): 56 data bytes
64 bytes from 10.10.10.10: icmp_seq=0 ttl=63 time=2.034 ms

--- my.host.local ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 2.034/2.034/2.034/0.000 ms

我想做類似的事情:如果 /64 bytes/ 然後列印類似的東西:“‘my.host.local’ is up”

問題是當我執行 /64 bytes/ 的正則表達式時,我失去了顯示主機名“my.host.local”的行,因此我不能使用該欄位來列印我的最終消息。

你會怎麼做?

乾杯,

使用變數儲存主機名:

awk '/^PING/ { host = $2 } /^64 bytes/ { print host " is up" }'

你可以做類似的事情

ping -c 1 $machine | awk '
 $1 == "PING" {host = $2}
 $2 == "bytes" {
   if ($1 == 64)
     print host " is up"
   else
     print host " did not ping 64 bytes"
 }
'

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