Arithmetic expressions using binary operators
AWK supports almost all basic arithmetic operators for building arithmetic expressions.These operators are binary operators; that is, they operate on two variables and are very similar to C language expressions.All these arithmetic operators follow the normal precedence rule.AWK supports the following arithmetic operators.
Addition (p + q):
This is represented by a plus (+
) symbol, which adds two or more numbers. These numbers could be variablesor constants.For example, we can add two numbers after assigning them to two variables as follows:
$ awk 'BEGIN{ p = 20; q = 30; print "( p + q ) = ",( p + q )}'
The output on execution of this code is as follows:
( p + q ) = 50
Now, we will use the marks.txt
sample file to calculate the sum of marks obtained by a student using the arithmetic operator, as follows:
$ vi sum.awk BEGIN { printf "%-6s\t%-7s\t%-7s\t%-7s\t%-7s\t%-7s\t%-5s\n", "Name", "Eng","Hindi","Maths","Science","Arts","Total" } ...