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 separately using the 'readarray' command in bash, so I write:
readarray myarray < demo.txt
The problem is that it doesn't work. If I try to print 'myarray' with:
echo $myarray
I get:
1 2 3
Also, if I write:
echo ${myarray[1]}
I get:
4 5 6
Instead of:
2
as I expected. Why is that? 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 withreadarray
:To expand on Damien's answer (and because I can't submit comments yet...) you just iterate on read. What I mean is something like the following
I hope you found a solution already (sorry to bump...). I stumbled upon this page while helping teach a friend and figured others may do the same.
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
as
echo "$myarray
will only outputmyarray[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:
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 usereadarray
.Paste the following code unaltered into an Ubuntu bash command line (not tried in any other environment)
Code
Output
Explanation
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/;
- prependdeclare my2d=(
to file$s/$/\n);
- append);
to fileNote
This gets too messy to be worth using if your array elements have whitespace in them
Sorry to bump but I believe there's an easy and very clean solution for your request: