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
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)
# 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}]";
Cell [2, 3] holds [23]
The four sed groups do the following:
s/^/"/g; - prepend double quotes to each lines/$/"/g; - append double quotes to each line1s/^/declare my2d=(\n/; - prepend declare my2d=( to file$s/$/\n); - append );to fileThis gets too messy to be worth using if your array elements have whitespace in them