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

后端 未结 6 1835
旧时难觅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 07:14

    Since 3 out of 5 answers ignore the OPs request to use readarray I'm guessing no one will downvote me for adding another that also fails to use readarray.

    Paste the following code unaltered into an Ubuntu bash command line (not tried in any other environment)

    Code

    # Create test array
    echo -e "00 01 02 03 04
    10 11 12 13 14
    20 21 22 23 24
    30 31 32 33 34" > original.txt;
    
    # Reformat test array as a declared bash variable.
    sed 's/^/"/g;  s/$/"/g;  1s/^/declare my2d=(\n/;  $s/$/\n);/' original.txt > original.sh;
    
    # Source the bash variable.
    source original.sh;
    
    # Get a row.
    declare row2=(${my2d[2]});
    
    # Get a cell.
    declare cell3=${row2[3]};
    echo -e "Cell [2, 3] holds [${cell3}]";
    

    Output

    Cell [2, 3] holds [23]
    

    Explanation

    The four sed groups do the following:

    1. s/^/"/g; - prepend double quotes to each line
    2. s/$/"/g; - append double quotes to each line
    3. 1s/^/declare my2d=(\n/; - prepend declare my2d=( to file
    4. $s/$/\n); - append );to file

    Note

    This gets too messy to be worth using if your array elements have whitespace in them

提交回复
热议问题