在bash脚本中,我试图从命令输出中提取一些数据字段(在我的情况下是iwconfig)。
我想用收集的值创建一个csv文件。像:
Timestamp,BitRate,LinkQuality,SignalLevel,Missed beacon,...
1,270 Mb/s,100/100,-51 dBm,0,...
2,300 Mb/s,90/100,-43 dBm,0,...
字段在iwconfig的输出中用两个空格分隔。如果我可以将IFS变量设置为两个空格,我的问题就可以解决了。但我不知道这是否有效。 你会用什么来做? awk还是sed?
祝你好运
答案 0 :(得分:1)
回答你的问题:我会用awk。但是,我可能会使用python和单个regexp来捕获字典中的所有参数。
Bonus:我已经完成了使用gnu的grep在bash中执行你想要的操作(你需要的regexp可能因iwconfig输出依赖于设备而有所不同):
SLEEP=10 # time to sleep between samples
while true; do # or launch it as a cron task
TIMESTAMP=$(date +'%s')
IW=$(iwconfig wlan0)
# capture each parameter in a variable
IEEE=$(echo "$IW" | grep -oP '(?<=IEEE ).[^\s]*')
ESSID=$(echo "$IW" | grep -oP '(?<=ESSID:).[^\s]*')
BITRATE=$(echo "$IW" | grep -oP '(?<=Bit Rate=)\d+\s.[^\s]+(?=[\s]+Tx)')
TXPOWER=$(echo "$IW" | grep -oP '(?<=Tx-Power=)\d+\s.*')
RLL=$(echo "$IW" | grep -oP '(?<=limit:)\d')
RTSTHR=$(echo "$IW" | grep -oP '(?<=RTS thr:).+(?=[ ]+Fra)')
FRAGTHR=$(echo "$IW" | grep -oP '(?<=Fragment thr:).+')
TXPOWER=$(echo "$IW" | grep -oP '(?<=Tx-Power=)\d+ .*')
PM=$(echo "$IW" | grep -oP '(?<=Management:).*')
LQ=$(echo "$IW" | grep -oP '(?<=Quality=)\d+/\d+')
SIGLEV=$(echo "$IW" | grep -oP '(?<=level=).*')
RXNWID=$(echo "$IW" | grep -oP '(?<=nwid:)\d+')
RXCRYPT=$(echo "$IW" | grep -oP '(?<=crypt:)\d+')
RXFRAG=$(echo "$IW" | grep -oP '(?<=frag:)\d+')
RTERET=$(echo "$IW" | grep -oP '(?<=retries:)\d+')
RTIMISC=$(echo "$IW" | grep -oP '(?<=misc:)\d+')
RTMBEAC=$(echo "$IW" | grep -oP '(?<=beacon:)\d+')
#line
echo $TIMESTAMP,$BITRATE,$LQ,$SIGLEV,$RTMBEAC,...
sleep $SLEEP
done
输出示例:
1331848207,54 Mb/s,70/70,-37 dBm ,0,...
1331848217,54 Mb/s,70/70,-35 dBm ,0,...
1331848227,54 Mb/s,70/70,-34 dBm ,0,...
1331848237,54 Mb/s,70/70,-39 dBm ,0,...
1331848247,54 Mb/s,70/70,-35 dBm ,0,...
1331848257,54 Mb/s,70/70,-37 dBm ,0,...
答案 1 :(得分:0)
我认为这可行:
s=$(iwconfig $Interface)
s=${s// / }
s=${s// /,}
OIFS="$IFS"
IFS=','
arrIN=(${s// /,})
IFS=$OIFS
for value in "${arrIN[@]}"; do
echo Value: $value
done
我得到了这个输出:
Value: wlan0
Value:
Value: IEEE 802.11abgn
Value: ESSID:"Top Gear"
Value:
Value: Mode:Managed
Value: Frequency:2.452 GHz
Value: Access Point: F8:D1:11:71:56:B6
Value:
Value: Bit Rate=1 Mb/s
Value: Tx-Power=15 dBm
Value:
Value: Retry
Value: long limit:7
Value: RTS thr:off
Value: Fragment thr:off
Value: Encryption key:off
Value: Power Management:off
Value: Link Quality=49/70
Value: Signal level=-61 dBm
Value:
Value: Rx invalid nwid:0
Value: Rx invalid crypt:0
Value: Rx invalid frag:0
Value: Tx excessive retries:0
Value: Invalid misc:0
Value: Missed beacon:0
现在我可以用例如
直接创建我需要的行${arrIN[6]#*":"}