scripts - Finding maximum of added fields - Ask Ubuntu


given text file numbers.data:

james:230:200:200 kory:140:204:240 hogan:293:234:100 logan:233:444:200 

fields delimited colon, simplest awk command add second, third, , fourth fields , find maximum out of 4 shown records? if possible, how print first field (name) of individual maximum field sum?

i.e. display: logan 877 , store variable.

you can do:

awk -f: '{for(i=2;i<=nf;i++) sum[$1]+=$i} end{for(j in sum) if (sum[j] > max) \            {n=j; max=sum[j]}; print n, max}' file.txt 
  • -f: sets field separator :

  • {for(i=2;i<=nf;i++) sum[$1]+=$i} iterates on fields , creates array sum field values starting second added

  • in end (end), for(j in sum) if (sum[j] > max) {n=j; max=sum[j]}; print n, max} iterates on array elements , find maximum number , print name in front

example:

% cat file.txt james:230:200:200 kory:140:204:240 hogan:293:234:100 logan:233:444:200  % awk -f: '{for(i=2;i<=nf;i++) sum[$1]+=$i} end{for(j in sum) if (sum[j] > max) {n=j; max=sum[j]}; print n, max}' file.txt logan 877 

Comments

Popular posts from this blog

download - Firefox cannot save files (most of the time), how to solve? - Super User

windows - "-2146893807 NTE_NOT_FOUND" when repair certificate store - Super User

sql server - "Configuration file does not exist", Event ID 274 - Super User