开发者

Awk, Sed : How to parse and sum values from a string

开发者 https://www.devze.com 2022-12-20 05:29 出处:网络
I\'ve a string like this Cpu(s):1.9%us,2.1%sy,1.5%ni, 94.5%id,0.8%wa,0.0%hi,0.1%si,0.0%st it represents the Cpu usage of my unix box.

I've a string like this

Cpu(s):  1.9%us,  2.1%sy,  1.5%ni, 94.5%id,  0.8%wa,  0.0%hi,  0.1%si,  0.0%st

it represents the Cpu usage of my unix box.

Now I need to apply awk and sed (i think) to extract the current load of my 开发者_运维知识库CPUs. I'd like to extract the 'us', 'sy', 'ni' values from the string and then I want to sum them.

The script should return 5.5 (1.9 + 2.1 + 1.5)... do you know how to achieve this?

Thanks a lot


well, you just need one awk command. No need for other tools

$ str="Cpu(s):  1.9%us,  2.1%sy,  1.5%ni, 94.5%id,  0.8%wa,  0.0%hi,  0.1%si,  0.0%st" 
$ echo $str | awk '{print $2+$3+$4+0}'
5.5


A pipeline with awk, sed and bc will do the trick:

echo 'Cpu(s): 1.9%us, 2.1%sy, 1.5%ni, 94.5%id, 0.8%wa, 0.0%hi, 0.1%si, 0.0%st'
    | awk '{print $2"+"$3"+"$4}'
    | sed 's/%..,//g'
    | bc

gives:

5.5

as expected.

The awk will pull out the three fields and print them with + between them:

1.9%us,+2.1%sy,+1.5%ni,

The sed will strip out all %.., sequences where .. is any two characters (us, sy and ni in this particular case):

1.9+2.1+1.5

The bc will evaluate that and give you the answer:

5.5


cpu='Cpu(s):  1.9%us,  2.1%sy,  1.5%ni, 94.5%id,  0.8%wa,  0.0%hi,  0.1%si,  0.0%st'
echo $cpu|sed 's/^Cpu.*: //;s/%..,*//g'|cut -f1-3 -d" "|tr " " "+"|bc
0

精彩评论

暂无评论...
验证码 换一张
取 消