Go to the first, previous, next, last section, table of contents.
The @command{awk} language uses the common arithmetic operators when evaluating expressions. All of these arithmetic operators follow normal precedence rules and work as you would expect them to.
The following example uses a file named `grades', which contains a list of student names as well as three test scores per student (it's a small class):
Pat 100 97 58 Sandy 84 72 93 Chris 72 92 89
This programs takes the file `grades' and prints the average of the scores:
$ awk '{ sum = $2 + $3 + $4 ; avg = sum / 3
> print $1, avg }' grades
-| Pat 85
-| Sandy 83
-| Chris 84.3333
The following list provides the arithmetic operators in @command{awk}, in order from the highest precedence to the lowest:
- x
+ x
x ^ y
x ** y
x * y
x / y
x % y
x + y
x - y
Unary plus and minus have the same precedence, the multiplication operators all have the same precedence, and addition and subtraction have the same precedence.
When computing the remainder of x % y,
the quotient is rounded toward zero to an integer and
multiplied by y. This result is subtracted from x;
this operation is sometimes known as "trunc-mod." The following
relation always holds:
b * int(a / b) + (a % b) == a
One possibly undesirable effect of this definition of remainder is that
x % y is negative if x is negative. Thus:
-17 % 8 = -1
In other @command{awk} implementations, the signedness of the remainder may be machine dependent.
Note: The POSIX standard only specifies the use of `^' for exponentiation. For maximum portability, do not use the `**' operator.
Go to the first, previous, next, last section, table of contents.