mvd
mvd

Reputation: 2720

How to pick out "second" value using awk?

The so-far expertly crafted script

iostat -p -x 1 2| grep $1[^[:digit:]] | awk '{print $9}'

will return two lines:

0.16
0.00

because iostat is taking two samples. But you already knew that. My question is since you and I both know it will be exactly two lines every time, how I pick out exactly the second?

Upvotes: 1

Views: 5922

Answers (3)

James Waldby - jwpat7
James Waldby - jwpat7

Reputation: 8711

Add NR==2 before {print $9} to tell awk to match record 2.

For example, on my system,

$ iostat -x /dev/sda 1 2 | grep sda

$ iostat -x /dev/sda 1 2 | grep sda | awk 'NR==1 {print $9}'

$ iostat -x /dev/sda 1 2 | grep sda | awk 'NR==2 {print $9}'

produced

sda               0.11     1.04    2.00    1.28   125.95    63.24   115.15     0.07   21.04    4.66   46.60   2.36   0.78
sda               0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00    0.00    0.00   0.00   0.00
0.07
0.00

where that "0.00" line is the result of the third command.

Additional note: It isn't necessary to run a separate grep command, as awk can match text. However, the awk script then needs an index variable. The first of the following examples is a simple grep to show what awk works on. The next two examples are straightforward awk code that has a match test to increment an index and another match test plus index test to print. The last example shows how to get rid of extra appearances of the match expression. Note, in these examples I replaced print $9 with print for clarity, and $1[^[:digit:]] with sda[^0-9]. Here are the examples which do the matching in awk instead of in grep:

$ iostat -p -x 1 2  | grep 'sda '
sda               0.11     1.04    2.00    1.28   125.70    63.16   115.09     0.07   21.04    4.66   46.57   2.36   0.78
sda               0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00    0.00    0.00   0.00   0.00

$ iostat -p -x 1 2  | awk '/sda[^0-9]/ {++t} t==1 && /sda[^0-9]/ {print}'
sda               0.11     1.04    2.00    1.28   125.70    63.16   115.09     0.07   21.04    4.66   46.57   2.36   0.78

$ iostat -p -x 1 2  | awk '/sda[^0-9]/ {++t} t==2 && /sda[^0-9]/ {print}'
sda               0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00    0.00    0.00   0.00   0.00

$ iostat -p -x 1 4  | awk '/sda[^0-9]/ && t++ && t==2 {print}'
sda               0.00     0.00    0.00    0.00     0.00     0.00     0.00     0.00    0.00    0.00    0.00   0.00   0.00

Upvotes: 7

nneonneo
nneonneo

Reputation: 179687

Combining head and tail lets you select any sequence of lines from the input:

(cmd) | tail -n+2 | head -n 1

gets the second line of input no matter how long the command's output is.

Upvotes: 2

Jay
Jay

Reputation: 3305

Pipe it to tail -1, this will select the last line.

iostat -p -x 1 2| grep $1[^[:digit:]] | awk '{print $9}' | tail -1

Upvotes: 2

Related Questions