[Techtalk] sum in awk-problem
Alain Tesio
alain at onesite.org
Tue Sep 21 21:20:59 EST 2004
On Tue, 21 Sep 2004 14:15:07 +0200 (MEST)
"Riccarda Cassini" <riccarda.cassini at gmx.de> wrote:
> { sum += $2; line[n++] = $0 }
>
> END {
> print "total sum =", sum;
>
> for (i=0; i<n; i++) {
> split(line[i], f);
> printf("%-25s %6.2f : %5.2f%%\n", f[1], f[2], f[2] / sum * 100);
> }
> }
Or you use awk arrays (aka hash tables or associative tables) to store
the data you want and not the lines themselves:
{ sum += $2; v[$1]=$2; }
END {
print "total sum =", sum;
for (key in v) {
printf("%-25s %6.2f : %5.2f%%\n", key, v[key], v[key] / sum * 100);
}
}
You may need two distinct sorted arrays or an array with (key,value) pairs if you
want to display the results in the same order as the input file.
Alain
More information about the Techtalk
mailing list