6.2.1 Arithmetic Operators

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.

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 program 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 awk, in order from the highest precedence to the lowest:

x ^ y
x ** y

Exponentiation; x raised to the y power. ‘2 ^ 3’ has the value eight; the character sequence ‘**’ is equivalent to ‘^’. (c.e.)

- x

Negation.

+ x

Unary plus; the expression is converted to a number.

x * y

Multiplication.

x / y

Division; because all numbers in awk are floating-point numbers, the result is not rounded to an integer—‘3 / 4’ has the value 0.75. (It is a common mistake, especially for C programmers, to forget that all numbers in awk are floating point, and that division of integer-looking constants produces a real number, not an integer.)

x % y

Remainder; further discussion is provided in the text, just after this list.

x + y

Addition.

x - y

Subtraction.

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

This definition is compliant with the POSIX standard, which says that the % operator produces results equivalent to using the standard C fmod() function, and that function in turn works as just described.

In other 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.