Main index

Introducing UNIX and Linux


Awk

Overview
What is 'awk'?
Invoking 'awk'
Naming the fields
Formatted output
      Operators used by Awk
Patterns
Variables
      Accessing Values
      Special variables
Arguments to 'awk' scripts
Arrays
Field and record separators
Functions
      List of Awk functions
Summary
Exercises

Naming the fields

In a shell script, $1, $2, etc., name the arguments of the script, but in an Awk script $1, $2, etc., name the fields of each record of data. The whole record is referred to as $0. To cause Awk to display something on standard output the command print can be used. Whenever the action print is performed, a Newline character is always displayed afterwards, just like the shell command echo. The following script copies standard input to standard output:

{ print $0 }

Worked example

Write a shell script to run Awk to display the first field of each line of standard input.
Solution: The Awk script is simple for this task, so we can enclose it within single quotes in the shell script. The Awk action is print $1 to be performed on each line. The Awk pattern to match every line is the null pattern, so that the Awk script becomes

{ print $1 }

To run Awk from a shell script, we require the utility awk, followed by this script (enclosed in quotes). Don't forget the comments!

# This shell script prints the first field of each
#   line of standard input
awk '{ print $1 }'

If you give print several arguments, it will concatenate their values before displaying them. The following Awk script displays each line of input enclosed in parentheses:

{ print "(" $0 ")" }

so for input

hello there
Chris

the output would be:

(hello there)
(Chris)

Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck