gawk: Arithmetic Ops

1 
1 6.2.1 Arithmetic Operators
1 --------------------------
1 
1 The 'awk' language uses the common arithmetic operators when evaluating
1 expressions.  All of these arithmetic operators follow normal precedence
1 rules and work as you would expect them to.
1 
1    The following example uses a file named 'grades', which contains a
1 list of student names as well as three test scores per student (it's a
1 small class):
1 
1      Pat   100 97 58
1      Sandy  84 72 93
1      Chris  72 92 89
1 
1 This program takes the file 'grades' and prints the average of the
1 scores:
1 
1      $ awk '{ sum = $2 + $3 + $4 ; avg = sum / 3
1      >        print $1, avg }' grades
1      -| Pat 85
1      -| Sandy 83
1      -| Chris 84.3333
1 
1    The following list provides the arithmetic operators in 'awk', in
1 order from the highest precedence to the lowest:
1 
1 'X ^ Y'
1 'X ** Y'
1      Exponentiation; X raised to the Y power.  '2 ^ 3' has the value
1      eight; the character sequence '**' is equivalent to '^'.  (c.e.)
1 
1 '- X'
1      Negation.
1 
1 '+ X'
1      Unary plus; the expression is converted to a number.
1 
1 'X * Y'
1      Multiplication.
1 
1 'X / Y'
1      Division; because all numbers in 'awk' are floating-point numbers,
1      the result is _not_ rounded to an integer--'3 / 4' has the value
1      0.75.  (It is a common mistake, especially for C programmers, to
1      forget that _all_ numbers in 'awk' are floating point, and that
1      division of integer-looking constants produces a real number, not
1      an integer.)
1 
1 'X % Y'
1      Remainder; further discussion is provided in the text, just after
1      this list.
1 
1 'X + Y'
1      Addition.
1 
1 'X - Y'
1      Subtraction.
1 
1    Unary plus and minus have the same precedence, the multiplication
1 operators all have the same precedence, and addition and subtraction
1 have the same precedence.
1 
1    When computing the remainder of 'X % Y', the quotient is rounded
1 toward zero to an integer and multiplied by Y.  This result is
1 subtracted from X; this operation is sometimes known as "trunc-mod."
1 The following relation always holds:
1 
1      b * int(a / b) + (a % b) == a
1 
1    One possibly undesirable effect of this definition of remainder is
1 that 'X % Y' is negative if X is negative.  Thus:
1 
1      -17 % 8 = -1
1 
1    In other 'awk' implementations, the signedness of the remainder may
1 be machine-dependent.
1 
1      NOTE: The POSIX standard only specifies the use of '^' for
1      exponentiation.  For maximum portability, do not use the '**'
1      operator.
1