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

Accumulation

Suppose you have two files of records, deposits and withdrawals, that contain a name field and an amount field separated by tabs. For each name, you 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 there are only withdrawals 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

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003