Awk as tool and scripting language
|
Built-In Functions
Awk has many useful functions that expand upon those already mentioned. The most important can be used to process text strings. You can concatenate, split up, search through, and replace text strings as you wish. Figure 2 shows a few of these functions, which are also included in the stringfunctions.sh files. You can copy the examples into shell and experiment with the functions before implementing them later in scripts.
Another useful function is getline , with which the output of a called Unix command can be piped in as an Awk variable (see the systemcalls.awk example in Listing 1). Using getline , you can also read data from files instead of directly from the command line. In this way, Awk can access data for formatting or comparing, for example.
Listing 1
Using getline with Awk
01 # Integrating Unix command 02 BEGIN { 03 "date +%x" | getline day; 04 "date +%T" | getline time; 05 printf("\nToday is %s and it is %s o'clock.\n", day, time); 06 }
Begin and End
Along with the conditions previously mentioned, you have the special patterns BEGIN and END . These instruction blocks serve an important purpose in evaluating files. Awk processes the commands in the BEGIN block before it reads in any data. The commands serve in initializing the script and setting variables. For example, if you want to change the delimiters for input and output, you can include the OFS variable within the block. The BEGIN block can also be used to output table headers.
The commands in the END block are parsed after reading the last row of data. They are often used to evaluate the input data. For example, you can calculate sums and averages or add footnotes to output tables.
If both blocks are in an Awk script, it's often worth saving the script in a separate file. You can create these files with a text editor such as Emacs or Vi. Most editors provide syntax highlighting to help in pairing curly braces for Awk.
« Previous 1 2 3 4 Next »
Buy this article as PDF
Pages: 5
(incl. VAT)