[Techtalk] sum in awk-problem
gebhard dettmar
gebhard.dettmar at student.hu-berlin.de
Wed Sep 22 20:44:13 EST 2004
On Tuesday 21 September 2004 21:20, Alain Tesio wrote:
> 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.
Works great. Seems to me, I have to do some reading on vectors and arrays ;-)
> Alain
Thanks a lot
Gebhard
More information about the Techtalk
mailing list