The 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.
Here is a file `grades' containing a list of student names and 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
This table lists the arithmetic operators in awk
, in order from
highest precedence to lowest:
- x
+ x
x ^ y
x ** y
x * y
x / y
awk
are
real numbers, the result is not rounded to an integer: `3 / 4'
has the value 0.75.
x % y
b * int(a / b) + (a % b) == aOne possibly undesirable effect of this definition of remainder is that
x % y
is negative if x is negative. Thus,
-17 % 8 = -1In other
awk
implementations, the signedness of the remainder
may be machine dependent.
x + y
x - y
For maximum portability, do not use the `**' operator.
Unary plus and minus have the same precedence, the multiplication operators all have the same precedence, and addition and subtraction have the same precedence.
Go to the first, previous, next, last section, table of contents.