LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   how to read values from a file (as part of a script) (http://www.linuxquestions.org/questions/linux-general-1/how-to-read-values-from-a-file-as-part-of-a-script-885578/)

AndrewJS 06-10-2011 08: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:

word1
word2
word3
etc.

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:

list="list.txt"
while (fscan(list,s1) !=EOF){
print (s1)
}

where:
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:
word1
word2
word3
the output of the above program would be:
word1
word2
word3

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

crabboy 06-10-2011 08:51 AM

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

rn_ 06-10-2011 09: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:
Code:

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 09: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 11:40 AM

I can not think of how many ways to do it is possible, but see something like these:
bash-script-read-file-into-array
Read file into array in Bash
reading-a-text-file-line-by-line-with-bash

good luck


All times are GMT -5. The time now is 02:40 AM.