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−

Syntax

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.

Example

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

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 −

Syntax

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

Example

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 −

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 −

Example

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

Output

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 DMCA.com Protection Status

AWK Topics