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

Say I have a text file called "demo.txt" that has a table in it:

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 does not 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:

 2 

as i expected. Why is this? How to access each row separately and in this row to access each member?

+6
source share
5 answers

This is the expected behavior. readarray will create an array in which each element of the array will be 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 row of data.

What you are looking for is a two-dimensional array. See for example.

If you need an array with the contents of the first row, you can do like this:

 $ read -a arr < demo.txt $ echo ${arr[0]} 1 $ echo ${arr[1]} 2 $ echo ${arr[2]} 3 
+9
source
 readarray rows < demo.txt for row in "${rows[@]}";do row_array=(${row}) first=${row_array[0]} echo ${first} done 
+2
source

To expand on Damien's answer (and because I cannot post comments yet ...), you simply repeat the reading. I mean the following:

 exec 5<demo.txt for i in `seq 1 ${numOfLinesInFile}` do read -a arr -u 5 for j in `seq 0 ${numOfColumnsMinus1}` do echo ${arr[$j]} done done 

Hope you found a solution already (sorry for the hit ...). I stumbled upon this page, helping teach a friend and decided that others could do the same.

+1
source

How to access each row separately and in this row to access each member?

In the Bash Reference Guide , Bash provides one-dimensional indexed and associative array variables. Thus, you cannot expect matrix[1][2] or similar to work. However, you can emulate matrix access using associative Bash arrays, where the key denotes multiple dimensions.

For example, matrix[1,2] uses the row "1,2" as the key of an associative array denoting the 1st row, 2nd column. Combining this with readarray :

 typeset -A matrix function load() { declare -aa=( $2 ) for (( c=0; c < ${#a[@]}; c++ )) do matrix[$1,$c]=${a[$c]} done } readarray -C load -c 1 <<< $'1 2 3\n4 5 6\n7 8 9' declare -p matrix 
+1
source

Sorry, but I believe there is a simple 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")' $ 
0
source

Source: https://habr.com/ru/post/977421/


All Articles