AWK Arrays - AWK

What is AWK Arrays?

AWK has associative arrays and best thing about it is – the indexes need not to be continuous set of number; we can use either string or number as an array index. Also, there is no need to initialize the size of an array in advance – arrays can expand/shrink at runtime.

Its syntax is as below−


Where array_name is the name of array, index is the array index, and value is any value assigning to the element of the array.

Creating Array

To gain more insight on array, let us create and access the elements of an array.


On executing this code, we will get the below output −


In the above example, we declare the array as fruits whose index is fruit name and the value is the color of the fruit. To access array elements, we use array_name[index] format.

Deleting Array Elements

For insertion, we used assignment operator. Similarly, we can use delete statement to remove an element from the array. The syntax of delete statement is as follows −


The below example deletes the element orange. Hence the command does not show any output.


Multi-Dimensional arrays

AWK only supports one-dimensional arrays. But you can easily simulate a multi-dimensional array using the one-dimensional array itself.

For example, given below is a 3x3 three-dimensional array −

In the above example, array[0][0] stores 100, array[0][1] stores 200, and so on. To store 100 at array location [0][0], we can use the following syntax −


Although we gave 0,0 as index, these will not be two indexes. In reality, it is just one index with the string 0,0.

The below example simulates a 2-D array −


On executing this code,we will get the below result:


We can even perform a set of operations on an array like sorting its elements/indexes. For that purpose, we can use assort and asorti functions.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

AWK Topics