Table of Contents

AWK - AWK Math Operations

Basic Math Operations

Assuming a file, test2.txt exists with following contents:

pens      10    1.99
pencils   20    3.99
staplers   5    8.99
rulers    12    2.50

Issue the following command:

awk '{print $1,"QTY: "$2,"PRICE: "$3,"TOTAL: "$2*$3}' test2.txt

returns:

pens QTY: 10 PRICE: 1.99 TOTAL: 19.9
pencils QTY: 20 PRICE: 3.99 TOTAL: 79.8
staplers QTY: 5 PRICE: 8.99 TOTAL: 44.95
rulers QTY: 12 PRICE: 2.50 TOTAL: 30

NOTE: The total multiples fields $2 with $3.


AWK supports the full range of arithmetic operators including:

OperatorDetails
+Adds numbers together.
-Subtracts.
*Multiples.
/Divides.
^Performs exponential mathematics.
%Gives the modulo (remainder).
++Adds one to the value of a variable.
+=Assigns the result of an addition operation to a variable.
Subtracts one from a variable.
-=Assigns the result of a subtraction operation to a variable.
*=Assigns the result of multiplication.
/=Assigns the result of division.
%=Assigns the result of a modulo operation.

Using a Variable

awk '{x=x+$2} {print x}' test2.txt

returns:

10
30
35
47

NOTE: This assigns a variable named x.

It has shown a running total and calculated an overall total of 47 items.


Advanced Example Using a Variable

awk '{x=x+($2*$3)}{print $1,"QTY: "$2,"PRICE: "$3,"TOTAL: "$2*$3,"BAL: "x}' test2.txt

returns:

pens QTY: 10 PRICE: 1.99 TOTAL: 19.9 BAL: 19.9
pencils QTY: 20 PRICE: 3.99 TOTAL: 79.8 BAL: 99.7
staplers QTY: 5 PRICE: 8.99 TOTAL: 44.95 BAL: 144.65
rulers QTY: 12 PRICE: 2.50 TOTAL: 30 BAL: 174.65

NOTE: This lists each record while assigning a total value and keeping a running balance.