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 ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.