Main index

Introducing UNIX and Linux


Awk

Overview
What is 'awk'?
Invoking 'awk'
Naming the fields
Formatted output
      Operators used by Awk
Patterns
Variables
      Accessing Values
      Special variables
Arguments to 'awk' scripts
Arrays
Field and record separators
Functions
      List of Awk functions
Summary
Exercises

Answer to chapter 11 question 1

For these problems, the solutions are in no way unique. See if you can devise different answers.

1a

The number of trains run is simply the number of lines in the file, which is the value of NR at the end of processing the data.

END { print NR }

1b

Use a variable count (say) to count the lines where the seventh field is 5:

$7 == 5 { count++ }
END { print count }

1c

Similar to the previous problem, but the count is incremented when field 7 is 5 and field 5 is fast:

$7 == 5 && $5 == "fast" { count++ }
END { print count }

1d

Rather than incrementing count by one each time a line of input relates to May (field 7 is 5), sum all the values of field 4:

{ passengers += $4 }
END { print passengers }

1e

As 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 }

1f

In 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) }

1g

In 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