7.7.2. Balance the Checkbook
This is a simple application that processes items in your
check register. While not necessarily the easiest way to balance
the checkbook, it is amazing how quickly you can build
something useful with awk.
This program presumes you have entered in a file the
following information:
1000
125 Market -125.45
126 Hardware Store -34.95
127 Video Store -7.45
128 Book Store -14.32
129 Gasoline -16.10
The first line contains the beginning balance.
Each of the other lines represent information
from a single check: the check number, a description
of where it was spent, and the amount of the check.
The three fields are separated by tabs.
Using negative amounts for checks allows positive amounts to
represent deposits.
The core task of the script is that it must get the beginning
balance and then deduct the amount of each check from that
balance. We can provide detail lines
for each check to compare against the check register.
Finally, we can print the
ending balance. Here it is:
# checkbook.awk
BEGIN { FS = "\t" }
#1 Expect the first record to have the starting balance.
NR == 1 { print "Beginning Balance: \t" $1
balance = $1
next # get next record and start over
}
#2 Apply to each check record, adding amount from balance.
{ print $1, $2, $3
print balance += $3 # checks have negative amounts
}
Let's run this program and look at the results:
$ awk -f checkbook.awk checkbook.test
Beginning Balance: 1000
125 Market -125.45
874.55
126 Hardware Store -34.95
839.6
127 Video Store -7.45
832.15
128 Book Store -14.32
817.83
129 Gasoline -16.10
801.73
The report is difficult to read, but later we will learn to fix the
format using the printf statement. What's
important is to confirm that the script is doing what we want.
Notice, also, that getting this far takes only a few minutes in awk.
In a programming language such as C, it would take you much longer to
write this program; for one thing, you might have many more lines of
code; and you'd be programming at a much lower level. There are any
number of refinements that you'd want to make to this program to
improve it, and refining a program takes much longer. The point is
that with awk, you are able to isolate and implement the basic
functionality quite easily.