LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to read data from file to use in shell script? (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-read-data-from-file-to-use-in-shell-script-477610/)

ozymandias 08-26-2006 02:55 PM

How to read data from file to use in shell script?
 
I'm trying to create a shell script that makes use of a data file with text on individual lines. I want the script to read the first line of the data file, then the second line etc. etc.
I can't seem to find out which command to use - sorry if this is a simple one!
I have tried a few man pages :study: but if you don't know which command you're looking for it's difficult to work backwards!
Cheers,

Oz

jp-lack 08-26-2006 03:28 PM

just to read the content of the file and echo them

Code:

#!/bin/sh
var=`cat file`
for i in $var; do
        echo $i
done

of course that you should verify if the file exist and bla bla bla ;)

ozymandias 08-26-2006 03:33 PM

aha! Thanks

Fredde87 10-27-2006 11:05 AM

may I hijack the thread and ask how to make it seperate the lines instead of the words? The above code will print every word and not sentences, so a file containing,

this is a test line
this is another test line

will return:
this
is
a
test
line
this
is
another
test
line

when I want a specified sentence (like line 2) to be placed in a variable.


Edit: I thought I knew SED pretty well, but I had never knew you could do it there. Here is an example if someone else needs it. LINE2="`sed -n '2p'file-location`"

pixellany 10-27-2006 12:47 PM

If I remember correctly, awk reads one line at a time.

Dragineez 10-27-2006 12:58 PM

Correct
 
Quote:

Originally Posted by pixellany
If I remember correctly, awk reads one line at a time.

You beat me to it!

pixellany 10-27-2006 01:04 PM

Quote:

Originally Posted by Fredde87
Edit: I thought I knew SED pretty well, but I had never knew you could do it there. Here is an example if someone else needs it. LINE2="`sed -n '2p'file-location`"

Need a space before file
The quotes are not needed, since the "`" makes a container

Thus: LINE2=`sed -n '2p' file-location`
Yes, sed is cool....;)

pixellany 10-27-2006 01:19 PM

Quote:

Originally Posted by Dragineez
You beat me to it!

My motorcycle is faster...;)


All times are GMT -5. The time now is 10:06 AM.