954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Reading a Text File into a shell variable

Hi everyone,

I am trying to write a shell script in which my variables take their values from a text file. The text file looks like the following:

[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,..,19]

One can say it is a large file so what I need to do is to write:

variabledin = [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,..,19]

In other words variabledin is equal to the content of the text file. I have looked on line for solutions on reading a file inside a shell but no success so far.

I would really appreciate any suggestion to solve this problem.

SakuraPink
Light Poster
31 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

Reading the contents into a variable is a simple task. Something like

VAR=`cat the.file`


should do the trick for you.
However, if you plan to access that data as an array of values (I'm assuming that this is your intent) then that will not work directly. To do that in Bash you would do something like:

DATA=`cat the.file | tr '[],' '() '`
eval VAR=${DATA}


Now you can access the variable as an array like ${VAR[2]} .

N.B. The tr portion of the example is to format the line you provide in a way that creates an array in Bash syntax. You may have to modify that for you own constraints.

L7Sqr
Practically a Master Poster
657 posts since Feb 2011
Reputation Points: 201
Solved Threads: 124
 

Thanks for your help. For my script the variable needs to keep the exact format so the fist way works well. But my problem is still unsolved as in my script I am using a python package therefore the script needs to be interpreted in the python environment, meaning that I am starting the script with

#!/usr/local/bin/pytho


and that gives me an error saying:SyntaxError: invalid syntax for

VAR=`cat the.file`


Do you know what I should do in this case?

SakuraPink
Light Poster
31 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

Sure looks like you want to use python scripting, not shell scripting. You might get more relevant and useful answers if you ask in the python forum.

Fest3er
Posting Whiz in Training
242 posts since Aug 2007
Reputation Points: 51
Solved Threads: 35
 

well thanks anyways.

SakuraPink
Light Poster
31 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You