tags:

views:

335

answers:

3

Hi all,
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

+1  A: 

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
paxdiablo
thanks for the explanation pax! this is really helpful
mickthompson
+5  A: 

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
ghostdog74
Why the +0? Seems to work without it too.
bromfiets
+0 converts the string to number(integer)
ghostdog74
A: 
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