UNIX in a Nutshell: System V Edition

UNIX in a Nutshell: System V EditionSearch this book
Previous: 10.5 Alphabetical Summary of Sed CommandsChapter 11Next: 11.2 Conceptual Overview

11. The Awk Scripting Language

Command-line Syntax
Conceptual Overview
Patterns and Procedures
Awk System Variables
Variables and Array Assignments
Group Listing of Awk Commands
Alphabetical Summary of Commands

This section presents the following topics:

For more information, see the Nutshell Handbook sed & awk.

11.1 Command-line Syntax

The syntax for invoking awk has two forms:

awk [options] 'script' var=value file(s)

awk [options] -f scriptfile var=value file(s)

You can specify a script directly on the command line, or you can store a script in a scriptfile and specify it with -f. Variables can be assigned a value on the command line. The value can be a literal, a shell variable ($name), or a command substitution (`cmd`), but the value is available only after a line of input is read (i.e., after the BEGIN statement). Awk operates on one or more files. If none is specified (or if - is specified), awk reads from the standard input.

The recognized options are:


Set the field separator to character c. This is the same as setting the system variable FS. Nawk allows c to be a regular expression. Each input line, or record, is divided into fields by white space (blanks or tabs) or by some other user-definable record separator. Fields are referred to by the variables $1, $2,..., $n. $0 refers to the entire record.

-v var=value

Assign a value to variable var. This allows assignment before the script begins execution. (Available in nawk only.)

For example, to print the first three (colon-separated) fields on a separate line:

awk -F: '{print $1; print $2; print $3}' /etc/passwd

Numerous examples are shown later in this section under "Patterns and Procedures."

Previous: 10.5 Alphabetical Summary of Sed CommandsUNIX in a Nutshell: System V EditionNext: 11.2 Conceptual Overview
10.5 Alphabetical Summary of Sed CommandsBook Index11.2 Conceptual Overview

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System