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

后端 未结 6 1758
旧时难觅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:58

    This is the expected behavior. readarray will create an array where each element of the array is a line in the input.

    If you want to see the whole array you need to use

    echo "${myarray[@]}"
    

    as echo "$myarray will only output myarray[0], and ${myarray[1]} is the second line of the data.

    What you are looking for is a two-dimensional array. See for instance this.

    If you want an array with the content of the first line, you can do like this:

    $ read -a arr < demo.txt 
    $ echo ${arr[0]}
    1
    $ echo ${arr[1]}
    2
    $ echo ${arr[2]}
    3
    

提交回复
热议问题