Cover V03, I05
Article
Listing 1
Sidebar 1

sep94.tar


Sidebar: Arrays in awk

awk arrays are defined as being associative, which means their subscripts may be strings as well as numbers. The following array element syntax builds an array of three strings:

alphabet["aa"]="alpha"
alphabet["bb"]="beta"
alphabet["cc"]="charlie"

Since arrays, like other awk variables, are not declared, referencing an array element in a conventional comparison creates the element if it did not previously exist:

if (alphabet["dd"] == "delta")
else
printf("%s\n", "created a null delta element")

awk provides a looping syntax which allows you to look at each element in an array:

for (i in alphabet)
printf(" %s %s\n", i, alphabet[i])

or a comparison without creating extra elements:

if ("dd" in alphabet)
printf("delta exists\n")
fi