假設下面的mpstat-log.txt文件,我如何解析文件的結果並獲得前4個CPU 0-3的%idle字段。我的猜測是這是grep,sed,cut或awk的工作,但我沒有足夠的經驗去知道哪個是最好的實用工具。bash腳本從文本文件解析特定的記錄號和字段?
#!/bin/bash for cpuIndex in {0..3} do # Get percent idle from line of specified cpuIndex cpuPercentIdle= # How to get a desired line and space separated field number? # Can you do math in a bash script ? cpuPercentUsed=$((100 - $cpuPercentId)) echo "CPU $cpuIndex : Idle=$cpuPercentIdle, Used=$cpuPercentUsed" done done
腳本輸出:
CPU 0 : Idle=45.18, Used=54.82 CPU 1 : Idle=96.33, Used=3.67 CPU 2 : Idle=95.65, Used=4.35 CPU 3 : Idle=72.09, Used=27.91
文件:mpstat的-log.txt的
Average: CPU %user %nice %sys %iowait %irq %soft %steal %idle intr/s Average: all 10.95 0.00 0.42 0.00 0.04 0.25 0.00 88.34 1586.71 Average: 0 51.50 0.00 3.32 0.00 0.00 0.00 0.00 45.18 0.00 Average: 1 3.67 0.00 0.00 0.00 0.00 0.00 0.00 96.33 2.66 Average: 2 4.35 0.00 0.00 0.00 0.00 0.00 0.00 95.65 0.00 Average: 3 27.57 0.00 0.33 0.00 0.00 0.00 0.00 72.09 997.34 Average: 4 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 10.96 Average: 5 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 0.00 Average: 6 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 0.00 Average: 7 0.00 0.00 0.00 0.00 0.00 1.67 0.00 98.33 575.75
預先感謝任何指導和提示!
如果有> 10個CPU,正則表達式'/ [0-3] /'會匹配太多 –
你們都爲寶貴的信息! –
@glenn好點。更新的答案涵蓋更多案例。謝謝 –