LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   for statement in bourne shell script (https://www.linuxquestions.org/questions/linux-general-1/for-statement-in-bourne-shell-script-464815/)

bujecas 07-17-2006 06:40 AM

for statement in bourne shell script
 
Hello,

I am parsing a file with entries like "word1 word2 word3". I need to parse each line, so I used a "for" statement in a Bourne shell script. Something like this:

Code:

for line in `cat $file`
do
  echo $line
done

In this simple example I want to print each line "word1 word2 word3" but instead it prints each word in a diferent line. The "for" statement seems not to distinguish between spaces and newlines...

Any idea to resolve this?
Thanks.

druuna 07-17-2006 06:52 AM

Hi,

Is this what you want:

Code:

for line in "`cat $file`"
do
  echo "$line"
done

You need to double quote the cat statement and the $line variable.

Hope this helps.

spooon 07-17-2006 06:58 AM

Quote:

Originally Posted by bujecas
Hello,

I am parsing a file with entries like "word1 word2 word3". I need to parse each line, so I used a "for" statement in a Bourne shell script. Something like this:

Code:

for line in `cat $file`
do
  echo $line
done

In this simple example I want to print each line "word1 word2 word3" but instead it prints each word in a diferent line. The "for" statement seems not to distinguish between spaces and newlines...

Any idea to resolve this?
Thanks.

Code:

cat $file | while read line
do
  echo $line
done

or
Code:

while read line
do
  echo $line
done < $file


theYinYeti 07-17-2006 07:32 AM

More generally, there are three main solutions when you want to read the output of something line by line:
Code:

something | while read line; do process "$line"; done
or
Code:

SaveIFS="$IFS"
IFS=$'\n'
for line in $(something); do process "$line"; done
IFS="$SaveIFS"

or
Code:

while read line; do process "$line"; done < <(something)
Yves.


All times are GMT -5. The time now is 07:21 AM.