LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 638|回复: 2

sed & awk 中的一个例子[已解决]

[复制链接]
发表于 2005-10-26 15:36:24 | 显示全部楼层 |阅读模式
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 的值 怎么没有改变?
发表于 2005-10-27 13:54:11 | 显示全部楼层
announce this: "The three fields are separated by tabs."

it means:   126<tab>Hardware<space>Store<tab>34.95
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-10-27 15:12:01 | 显示全部楼层
thanks.
正是如此。
我把它复制到VI中时,后面的tab变成了空格。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表