Introducing UNIX and Linux |
AwkOverview |
Answer to chapter 11 question 1For these problems, the solutions are in no way unique. See if you can devise different answers. 1aThe number of trains run is simply the number of lines in the
file, which is the value of END { print NR } 1bUse a variable $7 == 5 { count++ } END { print count } 1cSimilar to the previous problem, but the count is incremented
when field 7 is $7 == 5 && $5 == "fast" { count++ } END { print count } 1dRather than incrementing { passengers += $4 } END { print passengers } 1eAs the previous example, but the incremented fare total depends on the value of field 5. The solution presented here does the calculation in pence, and converts to pounds only at the end. $5 == "local" { fares += 10*$3*$4 } $5 == "fast" { fares += 12*$3*$4 } $5 == "express" { fares += 15*$3*$4 } END { printf "%.2f\n", fares / 100 } 1fIn this case we have three variables for the different fare categories. $5 == "local" { localfares += 10*$3*$4 } $5 == "fast" { fastfares += 12*$3*$4 } $5 == "express" { expressfares += 15*$3*$4 } END { printf "%.2f\n", localfares*100/ \ (localfares+fastfares+expressfares) } 1gIn this solution, floating-point arithmetic is used throughout, all the calculations being performed in pounds. BEGIN { rate["local"] = 0.10 rate["fast"] = 0.12 rate["express"] = 0.15 } { cost = 100 + 5*$3 revenue = $3*$4*rate[$5] profit = revenue - cost printf "%d/%d %s-%s: ", $6, $7, $1, $2 if (profit > 0) printf "profit %.2f\n", profit else printf "loss %.2f\n", -profit } |
Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck