supernatural
supernatural

Reputation: 1197

Getting a row whose specific given column has max value in bash script

I have file as (the spacing may not be regular)

a  34 4
b 34 5
c 4  123
d 100   34
e 1  23

Now how to get the row having the max value according to the column say, 2nd column using bash script. The output should be :

d 100   34

Upvotes: 0

Views: 504

Answers (3)

Léa Gris
Léa Gris

Reputation: 19675

Alternative to awk:

sort -k2nr file | head -1

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 204628

This will work even if all of your key values are negative and won't print a blank line if your input file is empty:

$ awk '(NR==1) || ($2 > max){max=$2; rec=$0} END{if (NR) print rec}' file
d 100   34

Upvotes: 3

anubhava
anubhava

Reputation: 786241

You may use this awk:

awk '$2 > max{max=$2; r=$0} END{print r}' file
d 100   34

Upvotes: 2

Related Questions