O'Reilly logo

Learning AWK Programming by Shiwang Kalkhanda

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.awkBEGIN {        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]  : bmwarr[car] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required