DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Using awk

User-defined variables

awk also allows you to define your own variables, which you can use for storing data, doing arithmetic, and the like. To illustrate, consider computing the total population and the average population represented by the data in the file countries:

   { sum = sum + $3 }
   { print "Total population is", sum, "million"
     print "Average population of", NR, "countries is", sum/NR }
In general, awk initializes variables with the string value "" and the numeric value 0. Accordingly, sum is set to zero before it is used.

As you can see, to refer to a variable in awk you do not need to prefix it with ``$'' unless it is a field variable.

The first action accumulates the population from the third field; the second action prints the sum and average:

   Total population is 262 million
   Average population of 1 countries is 262
   ...
   Total population is 2201 million
   Average population of 10 countries is 220.1

Next topic: Number or string?
Previous topic: awk internal variables

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003