How To Read a File and Assign the line values to an Array?

i have this basic code that i wrote to read a file and place it's values to an array. the source/input file will have multiple strings on it that is separated by a whitespace.

sample_list.txt file contents:

ACCT1 TABLE1
ACCT2 TABLE2
ACCT3 TABLE3

script file: sample_list.sh

#!/bin/bash

vFileDir="sample_list.txt"

declare -a vLnArray

printf " \n"
#read the content of the file by line
while IFS= read vline
do
 vLnArray=("$vline")
 vStr1="${vLnArray[0]}"
 vStr2="${vLnArray[1]}"

 echo "vStr1: $vStr1"
 echo "vStr2: $vStr2"

 vLnCtr=$((vLnCtr+1))
done < "$vFileDir"

when i run the script it gives me this output:

vStr1: ACCT1 TABLE1
vStr2:
vStr1: ACCT2 TABLE2
vStr2:
vStr1: ACCT3 TABLE3
vStr2:

basically this is the expected output:

vStr1: ACCT1 
vStr2: TABLE1
vStr1: ACCT2 
vStr2: TABLE2
vStr1: ACCT3 
vStr2: TABLE3

please help thank you.

Hi, try:

#!/bin/bash

vFileDir="sample_list.txt"

printf " \n"
#read the content of the file by line
while read vStr1 vStr2
do
 echo "vStr1: $vStr1"
 echo "vStr2: $vStr2"

 vLnCtr=$((vLnCtr+1))
done < "$vFileDir"    

--
Note: in your sample code, if you still want to use arrays, in this case you would need to use:

vLnArray=($vline)

without the quotes, otherwise the shell will not split the variable vline into two separate fields.

1 Like

thanks so much both solutions works.

vLnArray=( $vline ) without quotes does word splitting (wanted) and glob matching (not wanted).
A safer method is to let the read do the word splitting, either into discrete variables (see post #2) or into an array as follows:

while read -a vLnArray
do
 vStr1="${vLnArray[0]}"
 vStr2="${vLnArray[1]}"