0

I have a requirement where I need to store n lines of a UNIX file to n variables. The number of files may vary so I need to use the loop. eg: A file abc.txt

table1
table2
table3

Now I need to store them in a variable say Var1,Var2 and Var3 (here number of lines are not fixed and can change).

Can someone please help me ?

thor
  • 21,418
  • 31
  • 87
  • 173

2 Answers2

0

I haven't tested it but it should work

IFS='\n' read -r -a data <<< "$line"

What above command does is, set IFS variable to new line character and do splitting of $line. Now for your case $line should contain whole file contain and you can get content of each line using ${data[0]},${data1} ...

For more information on IFS you can click here

By default, IFS is set to '\n'.If you want to split based on some other character, like comma(,), change the variable accordingly

Community
  • 1
  • 1
Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41
  • Thanks Ashish. I want each line of the file to be assigned to a separate varable. I could find the maimum line by using wc-l and then for eg: For 4 different lines I want to create 4 variables and assign each line to a new variable like var1,var2,var3 and var4. – user3568369 Jun 27 '16 at 07:56
  • Plz have a look at this http://stackoverflow.com/questions/10820343/how-can-i-generate-new-variable-names-on-the-fly-in-a-shell-script – Ashishkumar Singh Jun 27 '16 at 09:34
0

What is the purpose of saving it in variable, You can execute your logic at the time of reading line by line from file itself right? If you want to perform certain logic based on the occurrence of string, You can follow some other codes rather than assigning them to different variables / array and iterate them again.

JP Bose
  • 22
  • 5