7beggars_nnnnm
7beggars_nnnnm

Reputation: 777

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?

Upvotes: 2

Views: 931

Answers (2)

anubhava
anubhava

Reputation: 786271

You may use this awk:

awk '$1+0 != $1 {next} FNR==NR {if (max < $1) max=$1; next} $1 == max' file{,}

9.0    10
9.0    19

Note that we compute max in first phase and then in 2nd phase print all records that have $1 same as max value.

PS: Your sample input is not pipe delimited as you are using in your question but if you have pipe delimited file then use:

awk -F'|' '$1+0 != $1 {next} FNR==NR {if (max < $1) max=$1; next} $1 == max' file{,}

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133770

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.

Upvotes: 2

Related Questions