-   Linux - General (
-   -   how to read values from a file (as part of a script) (

AndrewJS 06-10-2011 09:13 AM

how to read values from a file (as part of a script)
I want to read values from a file...these are basically one word values, that is to say that the text file I want to read from contains lines of word length 1, as in:


I actually only need the first word of the file and I want to assign it to a variable.
I am not very familiar with UNIX but I have practice with a UNIX-based software, and in this software, the method of sequentially reading values from a text file is the following:

while (fscan(list,s1) !=EOF){
print (s1)

s1 is string variable
list is a list variable that goes through the text file sequentially
fscan is a task the sets the value of s1 to the current value of list
The above program would read through to the end of file and print the value of each word.
so say if I had a file list.txt with entries:
the output of the above program would be:

My question is, what tasks and variables can be used to get the same result in UNIX?
And also regarding the list does one declare and assign values to such variables in UNIX?

crabboy 06-10-2011 09:51 AM

May I ask what you are trying to accomplish? Sounds a lot like an assignment for a class.

rn_ 06-10-2011 10:21 AM

well let's hope this is not a homework assignment.... if you just need to get the first word into a variable, you could simply use:

s1=`head -1 list.txt`
for more info: 'man bash', 'man head'

if you need to read each word and process it, look at the for loop in the bash man page and also 'man cat'

AndrewJS 06-11-2011 10:05 AM

Thanks to both comments...and no, this isn't a class assignment :)
like I said I often use a unix based software (an astronomy package) that has a programming language like that shown in my first post, however I needed a unix variable for a tiny part of a script (that I wrote for the astronomy package).

lithos 06-13-2011 12:40 PM

I can not think of how many ways to do it is possible, but see something like these:
Read file into array in Bash

good luck

All times are GMT -5. The time now is 03:02 PM.