2009-04-02

bash - read a file line by line instead of word by word

bash script read a file word by word rather then line by line. That means if you have a file with the below contents :





<start of file>

The quick brown fox jumps over the lazy dog

<end of file>

and you read & display it using :
for reading in $(cat /some/directory/some-file);
do
echo $reading;
done

The output would be :
<start of output>
The
quick
brown
fox
jumps
over
the
lazy
dog
<end of output>

instead at time we want it to display :
<start of output>The quick brown fox jumps over the lazy dog<end of output>


That sucks. As there is a lot of time we need bash to read the file line by line instead of word by word. Fortunately, we are using open source. Our predecessors have predicted the monkeys would step on this tragedy banana skin. Below are some solutions to let bash read a file line by line rather then word by word :

Solution 1 : using while do loop and read
cat some-file | while read theline;
do
echo $theline;

. . .

. . .

. . .

done

Advantage : quick & dirty

Disadvantage : the operation within the while do loop cannot contain "read" operation as it wont stop to execute it.



Solution 2 : meddle with IFS (Internal Field Separator)
#store the old IFS first
oldifs = $IFS

#then assign the new IFS we want it to be, which is new line
IFS = $ '\ n'

#the usual for do loop which this time it will use the new
#IFS we assigned
for theline in $ (cat some-file);
do
echo $theline;
. . .
. . .
. . .
done

#restore the Internal Field Separator
IFS = $

Voila !!!

No comments: