Awk as tool and scripting language

Slashdot it! Delicious Share on Facebook Tweet! Digg!

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 files. You can copy the examples into shell and experiment with the functions before implementing them later in scripts.

Figure 2: Awk provides a series of useful functions for processing text strings.

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.

Buy this article as PDF

Express-Checkout as PDF

Pages: 5

Price $0.99
(incl. VAT)

Buy Ubuntu User

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content