Command-Line Syntax

The syntax for invoking awk has two basic forms:

awk [-v var=value] [-Fre] [--] 'pattern { action }' var=value datafile(s)
awk [-v var=value] [-Fre] -f scriptfile [--] var=value datafile(s)

An awk command line consists of the command, the script and the input filename. Input is read from the file specified on the command line. If there is no input file or “-” is specified, then standard input is read. The -F option sets the field separator (FS) to re.

The -v option sets the variable var to value before the script is executed. This happens even before the BEGIN procedure is run. (See the discussion below on command-line parameters.)

Following POSIX argument parsing conventions, the "--" option marks the end of command-line options. Using this option, for instance, you could specify a datafile that begins with “-”, which would otherwise be confused with a command-line option.

You can specify a script consisting of pattern and action on the command line, surrounded by single quotes. Alternatively, you can place the script in a separate file and specify the name of the scriptfile on the command line with the -f option.

Parameters can be passed into awk by specifying them on the command line after the script. This includes setting system variables such as FS, OFS, and RS. The value can be a literal, a shell variable ($var) or the result of a command (`cmd`); it must be quoted if it contains spaces or tabs. Any number of parameters can be specified.

Command-line parameters ...

Get sed & awk, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.