Text-Processing
grep 用於 speedtest 輸出中的多個字元串
我在 BASH 腳本中使用speedtest CLI,並嘗試盡可能僅使用一行來獲取輸出。
Speedtest 的典型輸出:
Speedtest by Ookla Server: (censored) ISP: (censored) Latency: 93.85 ms (222.66 ms jitter) Download: 85.75 Mbps (data used: 134.8 MB) Upload: 5.68 Mbps (data used: 6.2 MB)
我想獲取延遲、下載速度、上傳速度和抖動。
Most ideal format: Download Speed: xx Mbps Upload Speed: xx Mbps Latency: xx ms Jitter: xx ms
我目前的測試程式碼使用了 2 個浪費的語句:
dl_speed=`speedtest | grep "Download: " | head -2 | tail -1 | awk {'print$2'} | cut -f1 -d:` ul_speed=`speedtest | grep "Upload: " | head -2 | tail -1 | awk {'print$2'} | cut -f1 -d:` echo "Download Speed: $dl_speed Mbps" echo "Upload Speed: $ul_speed Mbps"
使用 GNU awk。我至少使用了一個空格和
(
欄位分隔符。將此附加到您的speedtest
命令中。| awk 'BEGIN{ FS=" +|\\(" }; /Download/{ dow=$3 " " $4 }; /Upload/ { upl=$3 " " $4 }; /Latency/ { lat=$3 " " $4 }; /jitter/ { jit=$6 " " $7 }; END{ print "Download Speed:", dow; print "Upload Speed:", upl; print "Latency:", lat; print "Jitter:", jit }'
輸出到標準輸出:
下載速度:85.75 Mbps 上傳速度:5.68 Mbps 延遲:93.85 毫秒 抖動:222.66 毫秒
speedtest | tr -d '(:' | \ awk '/Download|Upload/ {print $1 " Speed: ",$2,$3} /Latency/ {print $1":",$2,$3} /jitter/ {print "Jitter:",$4,$5}'
給
Latency: 93.85 ms Jitter: 222.66 ms Download Speed: 85.75 Mbps Upload Speed: 5.68 Mbps