Search code examples
regexbashawkdisk-ioiowait

Getting iowait with top and awk


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


Solution

  • 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]}}'