ahelix
ahelix

Reputation: 23

awk: get maximum values and the fields that correspond to the values

Here are ways to get the maximum/minimum values of a row using awk.

AWK - find min value of each row with arbitrary size

However, I would need to go one step further by printing the fields that hold the max/min values. For example, the max value for a row is 100 and it is located at $13, so the output should be 100 and 13. Is this beyond awk?

Upvotes: 1

Views: 352

Answers (1)

Kent
Kent

Reputation: 195039

You can do in this way:

awk '{max=$1;c=1;for(i=2;i<=NF;i++)if($i>max){c=i;max=$i} printf "max:%s, column:%s\n",max, c}'

for example:

kent$  echo "1 4 3 2 6 5 8"|awk '{max=$1;c=1;for(i=2;i<=NF;i++)if($i>max){c=i;max=$i} printf "max:%s, column:%s\n",max, c}' 
max:8, column:7

Upvotes: 1

Related Questions