Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev
Chapter 7: awk Revisited
Next

Doing arithmetic with awk

You can easily, do the arithmetic with awk as follows

$ cat > math
{
  print $1 " + " $2 " = " $1 + $2
  print $1 " - " $2 " = " $1 - $2
  print $1 " / " $2 " = " $1 / $2
  print $1 " x " $2 " = " $1 * $2
  print $1 " mod " $2 " = " $1 % $2
}

Run the awk program as follows:

$ awk -f math
20 3
20 + 3 = 23
20 - 3 = 17
20 / 3 = 6.66667
20 x 3 = 60
20 mod 3 = 2
(Press CTRL + D to terminate)

In above program print $1 " + " $2 " = " $1 + $2, statement is used for addition purpose. Here $1 + $2, means add (+) first field with second field. Same way you can do - (subtraction ), * (Multiplication), / (Division), % (modular use to find remainder of division operation).


Prev
Home
Next
Predefined variables of awk
Up
User Defined variables in awk