Search code examples
indexingawkmaxline

awk - Print all lines containing the Max value found in the initial analysis


I have the following AWK command.

(awk 'max=="" || $1 > max {max=$1; l=$0} END{ print l}' FS="|" $STAGE_FILE) < input.txt

My intention is to be able to extract print the line that has the Max value in column 1. But considering the file input.txt below:

0.0008    6
9.0    10
9.0    19
0.7    33

the output I'm getting is

9.0    19

But what I wish would be

9.0    10
9.0    19

when I have two max values, in this case 9 (in the first column), the command only printed one of the rows and not all that have the Max value of 9.

What change in my code would allow you to print all lines with Max value of 9?


Solution

  • With your shown attempts, please try following.

    awk '
    {
      max=(max>$1?max:$1)
      arr[$1]=(arr[$1]?arr[$1] ORS:"")$0
    }
    END{
      print arr[max]
    }
    ' Input_file
    

    Explanation: Adding detailed explanation for above.

    awk '                                 ##Starting awk program from here.
    {
      max=(max>$1?max:$1)                 ##Creating max to get maximum value as $1 per line.
      arr[$1]=(arr[$1]?arr[$1] ORS:"")$0  ##Creating array arr with index of 1st field and keep adding its value to it with a new line.
    }
    END{                                  ##Starting END block of this program from here.
      print arr[max]                      ##Printing arr with index of max here.
    }
    ' Input_file                          ##Mentioning Input_file name here.