user3731374
user3731374

Reputation: 201

parsing string to two-dimensional array

please help me. I have string (all times changing, not constant) like this :

id1 name1 key1
id2 name2 key2
id3 name3 key3
...

how using bash i can put's this values to two-dimensional array?

in result for example having :

array[1][1] -> id1
array[1][2] -> name1
array[1][3] -> key1
array[2][1] -> id2
array[2][2] -> name2
...

TY for the help

Upvotes: 1

Views: 569

Answers (1)

Maxim Akristiniy
Maxim Akristiniy

Reputation: 2126

Bash does not support multidimensional arrays.
You can simulate them for example with hashes, but need care about the leading zeroes and many other things.

for example :

var="id1 name1 key1"

declare -A matrix
num_rows=1
num_columns=3

read -a array <<< ${var}

matrix[1,1]=${array[0]}
matrix[1,2]=${array[1]}
matrix[1,3]=${array[2]}


for ((j=1;j<=num_columns;j++)) do
    for ((i=1;i<=num_rows;i++)) do
        echo ${matrix[$i,$j]}
    done    
done

Upvotes: 1

Related Questions