home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Book HomeLinux in a NutshellSearch this book

13.6. Variable and Array Assignments

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

FS = ","

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

Arrays can be created with the split function (see the listing in Section 13.8, "Alphabetical Summary of Commands"), or they can simply be named in an assignment statement. Array elements can be subscripted with numbers (array[1]) or with names. For example, to count the number of occurrences of a pattern, you could use the following script:

/pattern/ { array["/pattern/"]++ }
END { print array["/pattern/"] }

In gawk, variables need not be declared previous to their use, nor do arrays need to be dimensioned; they are activated upon first reference. All variables are stored as strings but may be used either as strings or numbers. gawk will use the program script context to determine whether to treat a variable as a string or a number, but the distinction also can be forced by the user. To force a variable to be treated as a string, catenate a null to the variable:

var ""

To force a variable to be treated as a number, add 0 to it:

var + 0

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.