2

How can I print lines between two patterns which meet a certain condition?

For instance for an input file partially containing the following:

Time         %MEM    %CPU    %SWAP
00:05:02      7.3     8.4     3.5
00:10:02      10      4.3     4.5
00:15:02      8.5     4.4     6.7
00:20:02      25.3    35.8    7.3
00:25:02      74.6    28.4    7.3
00:30:02      67.2    88.3    7.3
00:35:02      35.4    87.4    7.3
00:40:02      27.3    92.8    7.3
00:45:02      45.3    83.2    10.5
00:50:02      30      65.7    10.5
01:00:02      92.3    66.4    10.5
01:05:02      13.1    69.4    13.5
01:10:02      45.2    77.4    13.5
01:15:02      48.7    78.8    13.5
01:20:02      49.1    80.5    13.5
01:25:02      72      83.9    13.5
END

I would like to print the first time and swap value for each swap value larger than 7. So my output would be:

00:20:02   7.3
00:45:02   10.5
01:05:02   13.5

I have tried:

awk '/%SWAP/{flag=1;next}/End/{flag=0}flag' myFile

which prints all lines. I have also tried:

awk '/%SWAP/ {flag=1;next}
     /End/{flag=0}
     {if ($10 > max) {max=$10; print $1 " " $2 " " $4}}' myFile

but this gives me output from previous sections of the file for $4.

Does anyone have a solution for this? An explanation would be greatly appreciated.

1 Answer 1

3

You can say:

$ awk '($4>7 && $4!=swap) {swap=$4; print $1, $4}' file
00:20:02 7.3
00:45:02 10.5
01:05:02 13.5

That is, store the last value of SWAP bigger than 7 in the swap variable and keep comparing the value.

You can get a nicer output by setting the output field separator to tab: -v OFS="\t" or BEGIN {OFS="\t"}. Or you can also pipe to column -t.

3
  • Thanks for the response, but how would I get the lines between %SWAP and END? I am assuming that there is more to this file not in the same format as the posted part of the file.
    – dabadie
    Feb 26, 2015 at 10:47
  • Probably awk '/SWAP/ {p=1} /^END/ {p=0} (p && $4>7 && $4!=swap) {swap=$4; print $1, $4}' a suffices.
    – fedorqui
    Feb 26, 2015 at 10:50
  • 1
    @Stéphane Chazelas your edit was almost there: /SWAP/,/^END/ {if ($4>7 && $4!=swap) {swap=$4; print $1, $4}} would work.
    – fedorqui
    Feb 26, 2015 at 11:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .