Filename.txt
My First Line
My Second Line
::::While Loop:::
Program(whileloop.sh):
while read line
do
echo "$line"
done < Filename.txt
output:
My First Line
My Second Line
:::For Loop:::
Program(forloop.sh):
for line in $(cat Filename.txt)
do
echo $line
done
output:
My
First
Line
My
Second
Line
You might wonder why does the output generated by for loop is different.
Well in above example for has treated space as field separator .
But to achieve the above output you need to add next line as a separator.
Therefore the same code can be written as.
Program:
IFS=for i in $(cat Filename.txt)
do
echo $i;
done
output:
My First Line
My Second Line\n' # Specify next line as Field Separator.
for i in $(cat Filename.txt)
do
echo $i;
done
output:
My First Line
My Second Line
No comments:
Post a Comment