Skip to Content
sed & awk, 2nd Edition
book

sed & awk, 2nd Edition

by Dale Dougherty, Arnold Robbins
March 1997
Intermediate to advanced
432 pages
11h 31m
English
O'Reilly Media, Inc.
Content preview from sed & awk, 2nd Edition

System Variables That Are Arrays

Awk provides two system variables that are arrays:

ARGV

An array of command-line arguments, excluding the script itself and any options specified with the invocation of awk. The number of elements in this array is available in ARGC. The index of the first element of the array is 0 (unlike all other arrays in awk but consistent with C) and the last is ARGC - 1.

ENVIRON

An array of environment variables. Each element of the array is the value in the current environment and the index is the name of the environment variable.

An Array of Command-Line Parameters

You can write a loop to reference all the elements of the ARGV array.

# argv.awk - print command-line parameters
BEGIN { for (x = 0; x < ARGC; ++x)
	    print ARGV[x]
	print ARGC
}

This example also prints out the value of ARGC, the number of command-line arguments. Here’s an example of how it works on a sample command line:

$ awk -f argv.awk 1234 "John Wayne" Westerns n=44 -
awk
1234
John Wayne
Westerns
n=44
- 
6

As you can see, there are six elements in the array. The first element is the name of the command that invoked the script. The last argument, in this case, is the filename, “-”, for standard input. Note the “-f argv.awk” does not appear in the parameter list.

Generally, the value of ARGC will be at least 2. If you don’t want to refer to the program name or the filename, you can initialize the counter to 1 and then test against ARGC - 1 to avoid referencing the last parameter (assuming that there ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The AWK Programming Language, 2nd Edition

The AWK Programming Language, 2nd Edition

Alfred V. Aho, Brian W. Kernighan, Peter J. Weinberger

Publisher Resources

ISBN: 1565922255Supplemental ContentErrata Page