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

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

    Sorry to bump but I believe there's an easy and very clean solution for your request:

    $ cat demo.txt
    1 2 3
    4 5 6
    7 8 9
    $ while read line;do IFS=' ' myarray+=(${line}); done < demo.txt
    $ declare -p myarray
    declare -a myarray='([0]="1" [1]="2" [2]="3" [3]="4" [4]="5" [5]="6" [6]="7" [7]="8" [8]="9")'
    $
    

提交回复
热议问题