LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Bash: Reading file into array (https://www.linuxquestions.org/questions/linux-newbie-8/bash-reading-file-into-array-848005/)

ghantauke 12-02-2010 03:34 PM

Bash: Reading file into array
 
Assume I have a file named file.txt with the following contents
Code:

19 man
24 house
44 dyam
90 random

I want to read the file into array and store each line in each index. I've tried using the following code.
Code:

dataarray=($( < file.txt ))
It stores each word in each index rather than each line in each index.
Can someone please help me.

bigrigdriver 12-02-2010 05:37 PM

www.google.com/linux is your friend for anything GNU/Linux/Unix. I entered search terms "bash array input" and found this: http://www.linuxconfig.org/Bash_scripting_Tutorial. Scroll down to "8.2. Read file into bash array".

rigor 12-02-2010 06:00 PM

Naturally it is much less elegant than what you started with,
but you could always force bash to do what you want like this:


Code:

# Just to be formal, declare the array.
declare -a data_array



# Force reading of each line into one element of the array.

line_cnt=0

while :
    do

        read data_line

        if [ $? -ne 0 ]
            then
                break
        fi

        data_array[$line_cnt]="$data_line"

        (( line_cnt++ ))

    done  <  file.txt




# To verify one line per element, display the contents of one element per line.

line_num=0

while [  $line_num  -lt  $line_cnt  ]
    do

        echo "data_array[$line_num]=${data_array[$line_num]}"

        (( line_num++ ))

done


grail 12-02-2010 10:06 PM

Well I would think the simple loop would be fine:
Code:

while read -r line; do arr+=( "$line" ); done<file


All times are GMT -5. The time now is 04:18 PM.