LINUX AWK Tutorial Series | Chapter 10

Hello and Welcome to Chapter 10 of this series.

In this post, I am going to talk about the Multi-Dimensional Array. Please study previously posted sessions to understand better.

Multi-Dimensional Array is defined by a sequence of multiple indices. So, If I say 2-dimensional array so it would be having 2 indices.

The indices are concatenated with a separator. This separator is a built-in variable as SUBSEP.
Indices are converted as single strings.

example:

fun[1,2]="Value"

Numbers 1 and 2 are converted as strings.

If value of SUBSEP is # , it will set fun["1#2"] to "value"


Default value fo SUBSEP is "\034". It is a not printing character. It will not appear in data.

Example1:

How to declare a 2-dimensional array.

            Col1     Col2
Row1   X           A  
Row2   Y           B


Syntax:

ma is my array name


awk 'BEGIN {ma[1,1]="X";ma[1,2]="A";ma[2,1]="Y";ma[2,2]="B"}'


Example2:

Print an array value


[himanshu@oel7 AWK]$ awk 'BEGIN {ma[1,1]="X";ma[1,2]="A";ma[2,1]="Y";ma[2,2]="B"; print ma[2,1]}'
Y


Example3:

How to find out if an index sequence is present in a Multi-dimensional array.

We will use IN operator, I have explained that in the previous single dimensional array.
I have created an AWK script and executed it. The indexes should be parenthesis and separated by comma(,)

[himanshu@oel7 AWK]$ cat multi_array
BEGIN {
ma[1,1]="X";ma[1,2]="A";ma[2,1]="Y";ma[2,2]="B"; print ma[2,1]
if((2,1) in ma)
print "(2,1) present in MA"
else
print "(2,1) not present in MA"
}
[himanshu@oel7 AWK]$ awk -f multi_array
Y
(2,1) present in MA


Example4:

Create Transpose of a Matrix. We have studied that in Maths. It is created by converting the rows to columns and columns to rows.

AWK script: 

[himanshu@oel7 AWK]$ cat transpose_array
{
     if (max_nf < NF)
          max_nf = NF
     max_nr = NR
     for (x = 1; x <= NF; x++)
          matrix[NR, x] = $x
}

END {
     for (col = 1; col <= max_nf; col++) {
          for (row = 1; row <= max_nr; row++)
               printf("%s ", matrix[row, col])
          printf("\n")
     }
}

The file containing 2D array


[himanshu@oel7 AWK]$ cat 2d-array
1 2 3 4
5 5 7 9
9 10 14 12

Executing AWK now


if you observe array has been transposed.



Split Function in Array

It is used to split the string into pieces. Place various pieces into an array.

Syntax: split(string,arr,sep)

String: String to be chopped
arr: name of the array
sep: separator

Try to understand the below at home now

[himanshu@oel7 AWK]$ cat split_array
BEGIN{
a[1,1]="A";a[1,2]="B";a[2,1]="C"; a[2,2]="D"

for (iterator in a) {
    split(iterator,arr,SUBSEP)
    print arr[1] "," arr[2]
   }
}
[himanshu@oel7 AWK]$ awk -f split_array
2,1
2,2
1,1
1,2

More chapters to follow


If you like please follow and comment