Other AWK Patterns


Other AWK Patterns

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.

Listing 22.5: Generating a Data Table (on the CD-ROM at ./source/ch21/table.awk )
start example
  1  :       BEGIN {  2  :         for (i = 1 ; i <= 10 ; i ++ ) {  3  :           printf( "%2d %f %f %f\n", i, sqrt(i), log(i), rand() )  4  :         }  5  :       } 
end example
 

We could use a while loop instead of a for loop as shown in Listing 22.6.

Listing 22.6: Generating a Data Table Using a while Loop (on the CD-ROM at ./source/ch21/table2.awk )
start example
  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  :       } 
end example
 

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.




GNU/Linux Application Programming
GNU/Linux Application Programming (Programming Series)
ISBN: 1584505680
EAN: 2147483647
Year: 2006
Pages: 203
Authors: M. Tim Jones

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net