Tree55Topz
Tree55Topz

Reputation: 1142

Comparing numbers in a column

I am familiar with comparing numbers in a row using bash, but what if I wanted to compare columns? Like if i had a file with

4 2 5 7
6 1 3 8

And I want to find the largest out of each column

6 2 5 8

How can I do this using awk?

Upvotes: 2

Views: 198

Answers (2)

John1024
John1024

Reputation: 113834

Assuming that your data is in a file called "data":

$ awk '{for(j=1;j<=NF;++j){max[j]=(max[j]>$j)?max[j]:$j};mNF=mNF>NF?mNF:NF} END{for(j=1;j<=mNF;++j)printf " " max[j]; print "" }' data
 6 2 5 8

Or, with different output formatting:

$ awk '{for(j=1;j<=NF;++j){max[j]=(max[j]>$j)?max[j]:$j};mNF=mNF>NF?mNF:NF} END{for(j=1;j<=mNF;++j)print "max of column " j "=" max[j]}' data
max of column 1=6
max of column 2=2
max of column 3=5
max of column 4=8

The body of the above awk program consists of:

{ for(j=1;j<=NF;++j) {max[j]=(max[j]>$j)?max[j]:$j};mNF=mNF>NF?mNF:NF }

This loop is run for every line in the input file. The loop runs through every column (field) in that input line from 1 to the number of fields (NF). For each column, it checks to see if the current value is greater than the previous maximum. If it is, it updates the value in the max array.

Upvotes: 4

choroba
choroba

Reputation: 241828

Bash solution using arrays:

max=();
while read -a line ; do 
    for ((i=0; i<${#line[@]} ; i++)) ; do
        ((line[i]>max[i])) && max[i]=${line[i]}
    done
done < input
echo "${max[@]}"

Upvotes: 2

Related Questions