DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Programming with awk

Accumulation

Suppose we have two files, deposits and withdrawals, of records containing a name field and an amount field. For each name we want to print the net balance determined by subtracting the total withdrawals from the total deposits for each name. The net balance can be computed by the following program:

   awk '
   FILENAME == "deposits"     { balance[$1] += $2 }
   FILENAME == "withdrawals"  { balance[$1] -= $2 }
   END                        { for (name in balance)
                                    print name, balance[name]
   } ' deposits withdrawals
The first statement uses the array balance to accumulate the total amount for each name in the file deposits. The second statement subtracts associated withdrawals from each total. If only withdrawals are associated with a name, an entry for that name is created by the second statement. The END action prints each name with its net balance.
Next topic: Random choice
Previous topic: Word frequencies

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004