3

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.

2
  • 1
    I would break it up into two, one to run on NR%4==0 and one to run on (NR+1)%4==0. You'll also need to have two variables to track the two values you're watching. – DopeGhoti Dec 28 '16 at 16:26
  • 1
    For every line, update the max value. If NR%4==0 then print out max value and reset it. – icarus Dec 28 '16 at 16:29
4
awk '{for(i=1;i<=NF;i++) if($i>maxval) maxval=$i;}
     NR%4==0 { print maxval ; maxval= -1}'
0
0

Alternative, using an array.

awk '{x=split($0,a);asort(a);if(a[x]>maxval)maxval=a[x]}
     NR%4==0 { print maxval ; maxval= -1}'
4
  • Thank you, tried applying this, received an error message about the wrong number of arguments to function "asort", didn't seem to like (NR=1) – Henry Dec 28 '16 at 21:59
  • Odd, I'm on GNU Awk 3.1.7, maybe some compatibility issue. – steve Dec 28 '16 at 22:01
  • Probably, I've had similar issues with simple things in 'sed'. Appreciate it though. – Henry Dec 28 '16 at 22:33
  • @Cbhihe - I expect Henry has moved on to other problems in the (almost) 3 intervening years ;-) – steve Oct 13 '19 at 8:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.