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 arraysum
field values starting second addedin 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
Post a Comment