Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 297
user3206874 Avatar asked Oct 29 '14 15:10

user3206874


People also ask

What does Readarray do in bash?

The readarray reads lines from the standard input into an array variable: my_array. The -t option will remove the trailing newlines from each line. We used the < <(COMMAND) trick to redirect the COMMAND output to the standard input. The <(COMMAND) is called process substitution.

How do I read an array file in bash?

Use the readarray Method to Read a File Into an Array Using Bash. The readarray is a function that comes with Bash 4.0. This method should work for all versions of Bash greater than 4.0. If your version for Bash is less than 4.0, you can skip down to the next method, as readarray will not work for you.

How read file line by line in shell script and store each line in a variable?

We use the read command with -r argument to read the contents without escaping the backslash character. We read the content of each line and store that in the variable line and inside the while loop we echo with a formatted -e argument to use special characters like \n and print the contents of the line variable.


1 Answers

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 
like image 101
damienfrancois Avatar answered Oct 09 '22 07:10

damienfrancois