lynn
lynn

Reputation: 45

how to return the index of max of each line using awk

I have a file with many rows like this:

id  val1  val2  val3 val4
a  0.10  0.50  0.30  0.40
b  0.15  0.35  0.20  0.80
c  0.50  0.45  0.20  0.40
....

I want to output the index of the max value and also the max value of each row like this:

a val2 0.50
b val4 0.80
c val1 0.50
...

I used

awk '{m=$2;for(i=1;i<=NF;i++)if($i>m) m=$i;print $1,m}'

to output the max value, but not sure how to output its index (val# here) in the print command as well, thanks advance for any suggestions and ideas!

Upvotes: 1

Views: 446

Answers (2)

Inian
Inian

Reputation: 85580

You are almost on the right track, just maintain a new variable idx for storing the index as

awk 'NR>1{m=$2;for(i=2;i<=NF;i++)if($i>=m) { m=$i; idx=i }; print $1,"val"(idx-1),m}' file

will produce the output as you need. Also couple of points worth noting here 1) Skip the header line as it is not needed for processing NR>1 takes care of that and 2) start your loop from $2 and change the conditional to ($i>=m) as it can match the 2nd column too.

Upvotes: 1

James Brown
James Brown

Reputation: 37404

Another for awk:

awk 'NR==1{split($0,a);next}{m=0;for(i=2;i<=NF;i++)if($i>m){m=$i;n=i}print $1,a[n],m}' foo
a val2 0.50
b val4 0.80
c val1 0.50

Upvotes: 1

Related Questions