How to use ‘awk’ to determine the maximal value in multiple subsets of data within a file

awk

Good morning,

I am using awk and trying to determine the max value of multiple sets of data within a file. Let's say I have the data:

    1 2 3
  4 5 6 7 8
  9 8 7 6 5
    4 3 2
    1 2 3
  4 6 7 8 7
  7 8 7 6 5
    4 3 2

I would like the output to be:

9
8

As every four lines is a subset of data, and 9 is the max value of the first set, and 8 is the max value of the second. I'm piping the above data in the first code block to:

awk 'NR%4<4 || NR==4 {for(i=1;i<=NF;i++) if($i>maxval) maxval=$i;}; END { print maxval;}' > file

But it only returns the max value of the whole file:

9

I was wondering if it is possible to print a max value of every n lines (n=4 here) in one awk command, or do I need to break it up? I had thought the NR%4<4 || NR==4 would tell the rest of the function to execute on every four lines, but seems like it's looking at all the data and only determining one 'maxval'.

Thanks.

Best Answer

awk '{for(i=1;i<=NF;i++) if($i>maxval) maxval=$i;}
     NR%4==0 { print maxval ; maxval= -1}'
Related Question