Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using awk, how can I find the max value in one column, print it; then print the match value in another column

Let's say I have this data:

1  text1  1   1   5
2  text2  2   2   10 
3  text3  3   3   15
4  text4  4   4   50
5  text5  5   5   25

I obtain the max value of column #5 with this code:

awk 'BEGIN {a=0} {if ($5>0+a) a=$5} END{print a}' data.txt

My question is how do I add more parameters in that code in order to find the associated value in whatever column I choose (but just one)? For example, I want to find the max value of column #5 and the associated value from column #2

The output I want is:

50 text4

I don't know how to add more parameters in order to obtain the match value.

like image 313
Diego Avatar asked Oct 11 '25 11:10

Diego


2 Answers

Right way to do this is this awk:

awk 'NR==1 || $5>max { max=$5; val=$2 } END { print max, val }' file

50 text4

This sets max=$5 and val=$2 for the first record or when $5 is greater than max variable.

like image 129
anubhava Avatar answered Oct 16 '25 10:10

anubhava


When you find a new max then save both the new max and the associated value from column #2.

One idea, along with some streamlining of the current code:

$ awk '$5>(a+0) { a=$5; col2=$2 } END {print a, col2}' data.txt
50 text4

NOTE:

  • this assumes that at least one value in column #5 is positive; if all values in column #5 are negative then $5>(a+0) will always be false and a (and col2) will never get set, which in turn means print a, col2 will print a line with a single space; a better solution would be to set a to the first value processed and then go from there (see anubhava's answer for an example)
like image 21
markp-fuso Avatar answered Oct 16 '25 11:10

markp-fuso