How to use 'readarray' in bash to read lines from a file into a 2D array

后端 未结 6 1742
旧时难觅i
旧时难觅i 2021-02-04 06:35

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

6条回答
  •  死守一世寂寞
    2021-02-04 06:48

    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
    

提交回复
热议问题