0

I have a text file with several lines and would like to write a bash script that reads the text file and store each line in different variable.

Here is how my file looks like.

cat file.txt

 line1
 line2
 line3

I would like to get the following:

variable1=line1
variable2=line2
variable3=line3

Do you have any idea how can I do this?

Inian
  • 80,270
  • 14
  • 142
  • 161
say.ff
  • 373
  • 1
  • 7
  • 21
  • 2
    Use `readarray` (also known as `mapfile`) to read each line into an array. Then you can reference each line at the indexes `0 - n-1`. – David C. Rankin Jan 17 '19 at 02:54
  • what happens next will probably dictate the best solution. – karakfa Jan 17 '19 at 02:58
  • True, but without knowing the number of lines before-hand, it would be impossible to read each line into an independently named variable without some type of `nameref` scheme. – David C. Rankin Jan 17 '19 at 03:01
  • 1
    Put each line into an array and then reference them by index is probably a better idea, please see this answer https://stackoverflow.com/a/30988704/10340970 – Derek Nguyen Jan 17 '19 at 03:01

1 Answers1

2

This question is unique in a sense it does not duplicate into any of this, this or this. So answering the question henceforth.

You might need a loop that runs through the file and set variables on-the-fly as below.

n=1
while IFS= read -r "variable$n"; do
  n=$((n + 1))
done < file.txt

and print the variables to see the content retrieved

for ((i=1; i<n; i++)); do 
    var="variable$i"
    printf '%s\n' "${!var}"
done
Inian
  • 80,270
  • 14
  • 142
  • 161