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?
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?
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.
END{for(j=1;j<=NF;++j)printf "%s%s",max[j],(j==NF?"\n":FS)}' to print according to the desired output.END {for (j=1;j<=NF;j++) printf "%s ",max[j]; print ""} -- a bit less tricky;).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] FS; print RS }' file