|
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.
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, subtracting amount from balance.
{ print $1, $2, $3
print balance -= $3
}
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
我运行的结果是:
Beginning Balance: 1000
125 Market 125.45
1000
126 Hardware Store 34.95
1000
127 Video Store 7.45
1000
128 Book Store 14.32
1000
129 Gasoline 16.10
1000
balance 的值 怎么没有改变? |
|