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.

Recommended Answers

All 4 Replies

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.

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?

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.

well thanks anyways.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.