Search code examples
awkaixiostat

parse iostat output using awk


I'm trying to filter the output of the parameter avgserv from the read line, using awk.

The default output of my iostat command: iostat -D hdisk0 is as follow:

bash-4.4$ iostat -D hdisk0

System configuration: lcpu=32 drives=9 paths=126 vdisks=0

hdisk0          xfer:  %tm_act      bps      tps      bread      bwrtn
                          0.0      3.0K     0.1       98.3        2.9K
                read:      rps  avgserv  minserv  maxserv   timeouts      fails
                          0.0      0.8      0.0      0.0           0          0
               write:      wps  avgserv  minserv  maxserv   timeouts      fails
                          0.1      2.2      0.0      0.0           0          0
               queue:  avgtime  mintime  maxtime  avgwqsz    avgsqsz     sqfull
                          0.0      0.0      0.0      0.0        0.0         0.0
--------------------------------------------------------------------------------

Using: iostat -D hdisk0 | awk '/avgserv/' I've managed to print the lines which matches: avgserv

bash-4.4$ iostat -D hdisk0 | awk '/avgserv/'
                read:      rps  avgserv  minserv  maxserv   timeouts      fails
               write:      wps  avgserv  minserv  maxserv   timeouts      fails

But,

First, i'm only returning the Headers, without the Actual Values.

Second, I need to return the avgserv parameter, only for the read line. Not for the write line.

My finale output should containe only the value of avgserv parameter, and only for the read line:

0.8

After a some digging, I've managed to return only the avgserv parameter using: iostat -D hdisk0 | awk '/avgserv/ {print $3}'

But still, I'm getting the required parameter for Both lines (read and write), and again without the actual value.


Solution

  • Could you please try following.

    your_command | 
    awk '
    /avgserv/ && /read/{
      found=1
      next
    }
    found{
      print $2
      found=""
    }'
    

    One liner form of solution:

    your_command | awk '/avgserv/ && /read/{found=1;next} found{print $2;found=""}'
    

    Explanation: Adding explanation for above code.

    your_command |              ##Sending your command output as standard input to awk command.
    awk '                       ##Starting awk command from here.
    /avgserv/ && /read/{        ##Checking condition if a line has string avgserv AND read then do following.
      found=1                   ##Setting variable found value to 1 here.
      next                      ##next will skip all further statements from here.
    }                           ##Closing BLOCK for above condition here.
    found{                      ##Checking condition if found is NOT NULL then do following.
      print $2                  ##Printing 2nd field here.
      found=""                  ##Nullifying variable found here.
    }'                          ##Closing BLOCK for found condition here.