2

我有一份与以下内容相同的报告:

gold     1      1986    USA                 Americal Eagle
gold     1      1908    Austria-Hungary     Franz Josef 100 Korona
silver  10      1981    USA             Ingot
gold     1      1984    Switzerland         ingot
gold     1      1979    RSA                 Krugerrand
gold     0.5    1981    RSA                 Krugerrand
gold     0.1    1986    PRC                 Panda
silver   1      1986    USA                 Liberty dollar
gold     0.25   1986    USA                 Liberty 5-collar piece
silver   0.5    1986    USA                 Liberty 50-cent piece
silver   1      1987    USA                 Constitution dollar
gold     0.25   1987    USA                 Constitution 5-dollar piece
gold     1      1988    Canada              Maple Leaf

我想提取如下报告:

Gold pieces:                    9
Weight of gold pieces:           6.10
Value of gold pieces:       9729.50

这是我制作的代码:

BEGIN{}
$1 ~/^gold$/
{
  goldWeight += $2
  ++goldCounter
}
END{
  printf "Gold Pieces:\t\t%d\n" , goldCounter
  printf "Weight of gold pieces:\t\t%1.2f\n" , goldWeight
  printf "Value of gold pieces:\t\t%1.2f\n" , goldWeight*1771.00
}

该代码不起作用。我的问题在哪里?

4

1 回答 1

3

您需要模式后的第一个括号

$1 ~/^gold$/ {
  goldWeight += $2
  ++goldCounter
}

然后大括号中的位适用于模式。否则它适用于每一行。

于 2012-10-10T09:05:40.023 回答