UNIX in a Nutshell: System V Edition

UNIX in a Nutshell: System V EditionSearch this book
Previous: 11.5 OperatorsChapter 11
The awk Programming Language
Next: 11.7 User-Defined Functions
 

11.6 Variables and Array Assignments

Variables can be assigned a value with an = sign. For example:

FS = ","

Expressions using the operators +, -, /, and % (modulo) can be assigned to variables.

Arrays can be created with the split() function (see below), or they can simply be named in an assignment statement. Array elements can be subscripted with numbers (array[1], ..., array[n]) or with strings. Arrays subscripted by strings are called associative arrays.[2] For example, to count the number of widgets you have, you could use the following script:

[2] In fact, all arrays in awk are associative; numeric subscripts are converted to strings before using them as array subscripts. Associative arrays are one of awk's most powerful features.

/widget/ { count["widget"]++ }		Count widgets
END      { print count["widget"] }		Print the count

You can use the special for loop to read all the elements of an associative array:

for (item in array)
	process array[item]

The index of the array is available as item, while the value of an element of the array can be referenced as array[item].

You can use the operator in to see if an element exists by testing to see if its index exists (nawk only):

if (index in array)
	...

This sequence tests that array[index] exists, but you cannot use it to test the value of the element referenced by array[index].

You can also delete individual elements of the array using the delete statement (nawk only).

11.6.1 Escape Sequences

Within string and regular expression constants, the following escape sequences may be used. Note: The \x escape sequence is a common extension; it is not part of POSIX awk.

SequenceMeaningSequenceMeaning
\aAlert (bell)\vVertical tab
\bBackspace\\Literal backslash
\fForm feed\nnnOctal value nnn
\nNewline\xnnHexadecimal value nn
\rCarriage return\"Literal double quote (in strings)
\tTab\/Literal slash (in regular expressions)


Previous: 11.5 OperatorsUNIX in a Nutshell: System V EditionNext: 11.7 User-Defined Functions
11.5 OperatorsBook Index11.7 User-Defined Functions

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