Roberto Carlos
Roberto Carlos

Reputation: 45

How to find the max values from columns

I am trying to find the maxima in three columns of a file called data.dat. The idea is

5414 6267 3157 
4521 1235 5418
1366 6472 4598
5153 7814 5648
5414
7814
5648

I'm trying to use awk as

for k in {1..3};awk 'BEGIN {max = 0} {if ('$k'>max) max='$k'} END {print max}' data.dat;done

but I have not been lucky.

Upvotes: 1

Views: 74

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133518

Could you please try following, written and tested with shown samples in GNU awk.

awk '
{
  for(i=1;i<=NF;i++){
    arr[i]=(arr[i]>$i?arr[i]:$i)
  }
}
END{
  for(k=1;k<=NF;k++){
    print arr[k]
  }
}' Input_file

Explanation: Adding detailed explanation for above.

awk '                                    ##Starting awk program from here.
{
  for(i=1;i<=NF;i++){                    ##Start a for loop from 1st field to last field of current line.
    arr[i]=(arr[i]>$i?arr[i]:$i)         ##Creating array arr with index of column number and keeping only greater value by comparing its [revious value in each iteration.
  }
}
END{                                     ##Starting END block of this awk program from here.
  for(k=1;k<=NF;k++){                    ##Starting a loop from k=1 to till number of fields here.
    print arr[k]                         ##Printing value of arr with index of k here.
  }
}' Input_file                            ##Mentioning Input_file name here.

Upvotes: 3

David C. Rankin
David C. Rankin

Reputation: 84561

This is what awk arrays are made for. You can simply loop over each field, using the field number as the array index and comparing the value against the current field value. If it is greater, update the value at that index with the current value, e.g.

awk '{
    for (i=1; i<=NF; i++)
        if ($i > a[i])
            a[i] = $i
}
END {
    for (j = 1; j < i; j++)
        print a[j]
}' file

Example Use/Output

For example, with your data in the filename file, you can just open an xterm and select-copy the awk script above and middle-mouse paste in the current directory containing file to test, e.g.

$ awk '{
>     for (i=1; i<=NF; i++)
>         if ($i > a[i])
>             a[i] = $i
> }
> END {
>     for (j = 1; j < i; j++)
>         print a[j]
> }' file
5414
7814
5648

Upvotes: 2

Related Questions