Using a for loop in bash to read a file line by line can sometimes be very annoying, here’s a little trick to make it actually red it LINE BY LINE.
Right before you run your for loop in your script, set this:
IFS=\n
With the above environment variable set, you tell bash that the delimiter is now a new-line (\n) instead of a white space.
Example:
Let’s say you have a text file (foo.txt) containing the following lines:
1 2 3
a b c
Running the following code
#!/bin/bash for LINE in `cat foo.txt`; do echo $LINE; done
will result in this output:
1
2
3
a
b
c
That’s not what we want, we want per line, so we add the IFS environment variable to the code, like this:
#!/bin/bash IFS=\n for LINE in `cat foo.txt`; do echo $LINE; done
There you go, the output is now:
1 2 3
a b c
The delimiter is only changed for the duration of the script, so you don’t have to reset it or anything.
Happy coding!
hmm, thx for the IFS trick, but why not doin something like this:
#!/bin/bash
while read LINE
do
echo $LINE
done < foo.txt
Hi Ushi, thanks for your comment, though that won’t work.
Atleast, i tried, but failed.
This output is strange, why is there a “4” and a “5”? I got this:
[ushi@cato tmp]$ while read LINE; do echo $LINE; done < test
1 2 3
a b c
[ushi@cato tmp]$ cat test
1 2 3
a b c
Ow lol, well ignore the “4” and “5” i just made a new foo.txt file and had
in it :)