AWK can use associative arrays as a data structure, where indices can be numbers or strings.
AWK associative arrays do not need to declare their size in advance, because they can automatically grow or shrink at runtime.
The syntax format 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 look at how to create arrays and how to access array elements:
$ awk 'BEGIN {
sites["example"]="www.example.com";
sites["google"]="www.google.com"
print sites["example"] "\n" sites["google"]
}'
Executing the above command produces the following output:
www.example.com www.google.com
In the above example, we defined an array of sites. The indices of the array are the English abbreviations of the websites, and the values are the website addresses. You can access array elements using the following format:
array_name[index]
Deleting Array Elements
We can use the delete statement to delete array elements. The syntax format is as follows:
delete array_name[index
In the following example, the google element in the array is deleted (the delete command has no output):
$ awk 'BEGIN {
sites["example"]="www.example.com";
sites["google"]="www.google.com"
delete sites["google"];
print fruits["google"]
}'
Multidimensional Arrays
AWK itself does not support multidimensional arrays, but we can easily use one-dimensional arrays to simulate multidimensional arrays.
The following example is a 3x3 two-dimensional array:
100 200 300 400 500 600 700 800 900
In the above example, array
We used 0,0 as the index, but this is not two index values. In fact, it is a string index 0,0.
The following is an example of 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;
# 输出数组元素
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 gives 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 using asort to sort array elements, or using asorti to sort array indices, etc.