The awk programming language can be used for other tasks besides file processing. Consider this example that simply emits a table of various data ( Listing 22.5).
Here we illustrate an awk program that processes no input file (as our code exists solely in the BEGIN section, no file is ever sought). We perform a for loop using an integer iterator and emit the index, the square root of the index ( sqrt ), the natural logarithm of the index ( log ), and finally a random number between 0 and 1.
1 : BEGIN { 2 : for (i = 1 ; i <= 10 ; i ++ ) { 3 : printf( "%2d %f %f %f\n", i, sqrt(i), log(i), rand() ) 4 : } 5 : }
We could use a while loop instead of a for loop as shown in Listing 22.6.
1 : BEGIN { 2 : i = 1 3 : while (i <= 10) { 4 : printf( "%2d %f %f %f\n"", i, sqrt(i), log(i), rand() ) 5 : i++ 6 : } 7 : }
So awk gives us the basic looping and control constructs that we d expect from a high-level language, but within a pattern-matching architecture.
This tour hopefully gives you a taste for the capabilities of the awk programming language, but there is much more. Awk provides a number of other built-in functions for reading a line from the input file ( getline ), searching for a substring within a string ( index ), returning the length of a string ( length ), and an sprintf command for string formatting.