'Find a maximum value from the second column and print value from the first column in awk or bash
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 1:[1]
$ 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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | αғsнιη |
