Let\'s say I have a text file \'demo.txt\' who has a table in it like this:
1 2 3
4 5 6
7 8 9
Now, I want to read each line separat
How can accesses each line separately and in that line get access to each member?
Per the Bash Reference Manual, Bash provides one-dimensional indexed and associative array variables. So you cannot expect matrix[1][2]
or similar to work. However, you can emulate matrix access using a bash associative arrays, where the key denotes a multiple dimension.
For example, matrix[1,2]
uses the string "1,2" as the associative array key denoting the 1st row, 2nd column. Combining this with readarray
:
typeset -A matrix
function load() {
declare -a a=( $2 )
for (( c=0; c < ${#a[@]}; c++ ))
do
matrix[$1,$c]=${a[$c]}
done
}
readarray -C load -c 1 <<< $'1 2 3\n4 5 6\n7 8 9'
declare -p matrix