Arrays in AWK
July 29th, 2008Initializing an array:
The following code will create the months array. number_of_months will contain the length of the array (12).
number_of_months = split("Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec", months, ",");
Setting an array value using the key:
Array indexing in AWK starts at 1:
months[1] = "Jan";
Testing the existence of an array key:
if(2 in months)
{
printf("The 2nd Month: %s\n", months[2]);
}
Iterating through an Array
Iterating through an array can be done using the key. The key can then be used to access the values inside the array
Note: Using this method, the order of the keys in the loop is arbitrary:
for(key in months)
{
printf("Index %d: %s\n", key, months[key]);
}
Iteration can also be done using the incremental index method:
for (i=1; i<=number_of_months; i++)
{
printf("Index %d: %s\n", i, months[i]);
}
Associative Arrays:
together["pees"] = "carrots";
together["gin"] = "tonic";
Deleting array elements and arrays:
delete months[12]; # Removes that element of the array
delete months; # Deletes the array itself