Accessing elements in arrays
The ideal way to access an array element is to refer to that element via its index, as follows:
arr[index]
Here, arr
is the name of an array, and index
is the index of the desired element of the array that we want to access.
The following is a simple example of assigning and accessing AWK arrays:
$ vi arr_access.awk
BEGIN {
arr[30] = "volvo"
arr[10] = "bmw"
arr[20] = "audi"
arr[50] = "toyota"
arr["car"] = "ferrari"
arr[70] = "renault"
arr[40] = "ford"
arr[80] = "porsche"
arr[60] = "jeep"
print "arr[10] : ", arr["10"]
print "arr[car] : ", arr["car"]
print "arr[80] : ", arr["80"]
print "arr[30] : ", arr["30"]
}
$ awk -f arr_access.awk
The output of the execution of the preceding code is as follows:
arr[10] : bmw arr[car] : ferrari arr[80] : porsche arr[30] : volvo
In the preceding example, we can see that the array indexes are not in sequence. They don't begin...