Bash(awk) - Comparing numbers in a column -


i familiar comparing numbers in row using bash, if wanted compare columns? if had file with

4 2 5 7 6 1 3 8 

and want find largest out of each column

6 2 5 8 

how can using awk?

assuming data in 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, 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 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 run every line in input file. loop runs through every column (field) in input line 1 number of fields (nf). each column, checks see if current value greater previous maximum. if is, updates value in max array.


Comments

Popular posts from this blog

php - Magento - Deleted Base url key -

javascript - Tooltipster plugin not firing jquery function when button or any click even occur -

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -