Saturday, April 23, 2022

[SOLVED] Find a maximum value from the second column and print value from the first column in awk or bash

Issue

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 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?


Solution

$ 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


Answered By - James Brown
Answer Checked By - Mary Flores (WPSolving Volunteer)