Home > Software engineering >  Find a maximum value from the second column and print value from the first column in awk or bash
Find a maximum value from the second column and print value from the first column in awk or bash

Time:02-19

I found a solution how to find a minimum and maximum value in awk awk: find minimum and maximum in column But instead of printing max value. I want to print the value from the first column in row in which is maximum value and print it to another file My input:

 1.35571          65.2085
 1.36264          65.2541
 1.36957          65.3155
 1.37651          65.1064

Expected output

1.36957

Maybe I should use sort?

CodePudding user response:

$ awk '
$2>max || max=="" {   # or $2>=max, depending on if you want first or last
    max=$2
    val=$1
}
END {
    print val
}' file

Output:

1.36957

CodePudding user response:

to "keep all lines' of first column with equal maximum values" in 2nd column:

awk '$2>max || NR==1 { max=$2; data=$1; next }
     $2==max{ data= data ORS $1 }
END{ print data }' infile
  • Related