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.
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:
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) ...
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 ...
...which correctly returns: 550
You might recognize the 3rd column as the first 10 Fibonacci numbers. What is their sum?
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'.
We saw some 'equality operators' in Regex Comparisons. Here are a few more ...