manpagez: man pages & more
info gawk
Home | html | info | man

gawk: Arithmetic Ops

 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
      $ 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'
 '+ X'
      Unary plus; the expression is converted to a number.
 'X * Y'
 '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'
 '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 '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 '**'
© 2000-2018
Individual documents may contain additional copyright information.