2

For a benchmark script, I need to extract the iowait % right after a little operation.

For now, the best way I find was this: IOWAIT=top -bn2 | awk '$1~/Cpu/ {print $6}' | sed -n '2p' | tr -d '%wa,'

The correct output is something like 2.1:

First, if I didn't precise "-bn2", I don't know why, it is always 0.1% if I take the capture only 1 time. So I take the capture two time, then I awk to get the iowait field then I sed the second line and then I remove the "%wa"

FYI, here is the output of top -bn2 | grep Cpu

Cpu(s):  2.8%us,  0.4%sy,  0.0%ni, 96.6%id,  0.1%wa,  0.0%hi,  0.0%si,  0.0%st<br>
Cpu(s):  0.2%us,  2.9%sy,  0.0%ni, 87.1%id,  9.5%wa,  0.0%hi,  0.3%si,  0.0%st

My problem is the following: when I get one column at 100.0% (for example idle), it's shift the columnnumber so my awk doesn't work anymore and I get the "0.0%hi" field.

My questions is the following:

-How to tell awk to take to column with the "%wa" ?

If anybody have a best approach to what I'm looking to do, I'm of course very open to suggestion !

Thanks

Brice
  • 786
  • 4
  • 16

3 Answers3

5

2 ways to do it. You didn't say but I presume you're on linux (that top syntax doesn't work on osx), so this should work with iostat:

iostat -c|awk '/^ /{print $4}'

or with top:

top -bn2| awk -F"," '/Cpu/{if(p==0){p=1}else{split($5,a,"%");print a[1]}}'
bazzargh
  • 1,792
  • 10
  • 16
2

How about with grep alone:

top -bn2 | grep -o -E "[[:digit:]]*.[[:digit:]]%wa" | tr -d '%wa'
Timmah
  • 2,001
  • 19
  • 18
  • I accepted the bazzargh's answer has it is more relevant of my original question. However, I will go on your solution (with adding a sed to select the second line) as it is the one I'm fully understand ! Thanks again to both of you (and sorry I can't vote up for your answer) – Brice Feb 21 '14 at 13:41
0

All in one

top -bn2 | awk '$1~/Cpu/&&NR==2{for (i=1;i<=NF;i++)if ($i~/%wa/) {sub(/%wa,/,X,$i);print $i}}' 
BMW
  • 42,880
  • 12
  • 99
  • 116
  • Hi, thanks for your help too ! I didn't get any result when I try your suggestion, and as I'm not a awk regular nor bash, I absolutely can't debug it :( – Brice Feb 21 '14 at 11:41