awk awk awk

awk Computation

We mentioned that one of the reasons awk was developed was to have a scripting language that could do mathematical operations. Let's see how that's done.

1
2
3
4
5
6
7
8
9
10

Copy & paste the above lines into a text file and name it 'digits.txt'. We will use it to do some simple 'computational' operations.

The column is simply the first 10 numbers (note: they don't have to be in any order).

To add them all up we can do this:

awk '{ sum += $1 } END { print sum }' digits.txt

Which should result in: 55

What if we have more than 1 column of numbers? Here is another file (3col.txt) with 3 columns of numbers (tab-delimited) ...

1 10 1
2 20 1
3 30 2
4 40 3
5 50 5
6 60 8
7 70 13
8 80 21
9 90 34
10 100 55

We use the same structure as above, only replacing the $1 with the column number we want to add. So to add the 2nd column ...

awk '{ sum += $2 } END { print sum }' 3col.txt

...which correctly returns: 550

You might recognize the 3rd column as the first 10 Fibonacci numbers. What is their sum?

awk '{ sum += $3 } END { print sum }' 3col.txt

143 should be your result.

Here's how it works. First we set a variable 'sum' to be the aggregate sum of numbers in the 3rd column (field) by using the += arithmetic operator. END is a special pattern (see below).

Our last action is to print the value held in 'sum'.

Arithmetic Operators

We saw some 'equality operators' in Regex Comparisons. Here are a few more ...