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

I have a line 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 processor usage of my unix window.
Now I need to apply awk and sed (I think) to extract the current load on my processors. I would like to extract the values ​​from the string "us", "sy", "ni" from the string, and then I want to sum them up.
the script should return 5.5 (1.9 + 2.1 + 1.5) ... do you know how to achieve this?
Many thanks

+3
source share
3 answers

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
+6
source

awk, sed bc :

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

:

5.5

.

awk + :

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

sed %..,, .. - (us, sy ni ):

1.9+2.1+1.5

bc :

5.5
+1
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
source

Source: https://habr.com/ru/post/1733179/


All Articles