我正在嘗試對ifconfig | grep "RX packets"輸出的“RX 資料包”行中的所有位元組求和。
我怎么做?
這是我的代碼
#!/usr/lib/env bash
clear
result=0
while read i; do
line=${i##*'bytes'} | awk '{print $1;}'
(( "$result" ="$line" ))
echo "$result"
done <<< "$(ifconfig | grep "RX packets")"
另外:我應該如何以更好的方式提取這些位元組行,"$(ifconfig | grep "RX packets")"然后line=${i##*'bytes'} | awk '{print $1;}'看起來如此丑陋和復雜
if config | grep "RX packets"我的輸出:
RX packets 7817232 bytes 9337993347 (9.3 GB)
RX packets 1240058 bytes 83114376 (83.1 MB)
RX packets 0 bytes 0 (0.0 B)
RX packets 188707 bytes 27682805 (27.6 MB)
期望的結果 - 所有位元組的總和:
9337993347 83114376 27682805
uj5u.com熱心網友回復:
使用 shell 通過 while/read 回圈進行算術運算既慢又笨重。你可以簡單地做:
ifconfig | awk '/RX packets/{ s = $5 } END {print s}'
(這假定輸出的特定格式ifconfig,因此如果您在不同的平臺上使用它可能會失敗。)
uj5u.com熱心網友回復:
分配給變數時,即使在算術運算式中,也要使用不帶美元符號的變數名。
從命令串列中讀取時,使用行程替換而不是此處的字串。
此外,您不需要awk,您可以像洗掉其他部分一樣洗掉子字串。
#! /bin/bash
result=0
while read line; do
line=${line##*bytes} # Remove everything up to bytes.
line=${line%(*} # Remove everything starting from (.
(( result =line ))
done < <(ifconfig | grep "RX packets")
echo $result
uj5u.com熱心網友回復:
或者,使用sedand bash:
bytes=$(ifconfig | sed -n 's/.*RX packets.*bytes \([0-9]*\).*/\1/p')
echo $(( ${bytes//$'\n'/ } ))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/503781.html
