AWK Arrays
Category Programming Techniques
AWK can use associative arrays as a data structure, where the indices can be numbers or strings.
AWK associative arrays do not need to be declared with a specific size, as they can automatically grow or shrink at runtime.
The syntax for using arrays is:
array_name[index]=value
- array_name: the name of the array
- index: the array index
- value: the value assigned to the element in the array
Creating Arrays
Next, let's see how to create arrays and access array elements:
$ awk 'BEGIN {
sites["tutorialpro"]="www.tutorialpro.org";
sites["google"]="www.google.com"
print sites["tutorialpro"] "\n" sites["google"]
}'
Executing the above command, the output is:
www.tutorialpro.org
www.google.com
In the example above, we defined an array named sites, where the index is the website's English abbreviation and the value is the website's access address. Array elements can be accessed using the following format:
array_name[index]
Deleting Array Elements
We can use the delete statement to remove array elements, with the following syntax:
delete array_name[index]
In the following example, the google element in the array is deleted (the delete command does not produce output):
$ awk 'BEGIN {
sites["tutorialpro"]="www.tutorialpro.org";
sites["google"]="www.google.com"
delete sites["google"];
print sites["google"]
}'
Multidimensional Arrays
AWK does not natively support multidimensional arrays, but we can easily simulate them using one-dimensional arrays.
The following example is a 3x3 two-dimensional array:
100 200 300
400 500 600
700 800 900
In this example, array[0][0] stores 100, array[0][1] stores 200, and so on. To store 100 at array[0][0], we can use the following syntax: array["0,0"] = 100.
We used 0,0 as the index, but this is not two separate index values. In fact, it is a string index "0,0".
Here is an example simulating a two-dimensional array:
$ awk 'BEGIN {
array["0,0"] = 100;
array["0,1"] = 200;
array["0,2"] = 300;
array["1,0"] = 400;
array["1,1"] = 500;
array["1,2"] = 600;
# Output array elements
print "array[0,0] = " array["0,0"];
print "array[0,1] = " array["0,1"];
print "array[0,2] = " array["0,2"];
print "array[1,0] = " array["1,0"];
print "array[1,1] = " array["1,1"];
print "array[1,2] = " array["1,2"];
}'
Executing the above command yields the following result:
array[0,0] = 100
array[0,1] = 200
array[0,2] = 300
array[1,0] = 400
array[1,1] = 500
array[1,2] = 600
Many operations can be performed on arrays, such as sorting array elements using asort, or sorting array indices using asorti, among others.
** Share Your Notes
-
-
-