Avishi
Avishi

Reputation: 19

how to read file line by line and store value in array using shell script

How to read file line by line and store each line value in different array variable. For example file.txt contains below lines:

abc;2;1;3;4;5;6;7 
cba;1;2;3;4;5;6;7;8;9;
......
.......

So I need to read line by line and store each line value seprated by delimeter in different variable. Like for line 1

arr[0]=abc, arr[1]=2, arr[2]=1 and so on

and after reading first line it will read line 2 and store its value like:

arr[0]=cba, arr[1]=1, arr[2]=2 and so on

I have tried below code

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

for ((i=0; i < ${#arr[*]}; i++))
do
    echo "${arr[i]}"

done

But in this case I am getting whole line by line in arr[i]. I need to store this value of line in seprate variable as mentioned above.

Upvotes: 0

Views: 3822

Answers (1)

pacholik
pacholik

Reputation: 8972

Assuming you are using bash:

while read line; do
    varname=${line%%;*}
    IFS=';' read -a $varname <<< $line
done < file
  • read the file line by line
  • determine the name of the variable using bash's substring math
  • read into array using read -a

$ echo ${abc[0]} ${abc[1]}
abc 2
$ echo ${cba[0]} ${cba[1]}
cba 1

Upvotes: 1

Related Questions