0

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for reply.. but in my case <<< its not working. its giving error for this symbol <<<.
As I wrote, I'm assuming you are using bash. What shell are you using?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.