bash Line Parsing
9
Parsing newline-delimited data records in bash is simple, if you have this odd redirect up your sleeve. An annoying thing about bash is that it usually equates all whitespace characters, so the first block in the snippet won't let you use a file linewise, but will end up echoing each whitespace-delimited token on a separate line.
bash provides the "read" builtin which can be used to differentiate between newlines and spaces.
bash provides the "read" builtin which can be used to differentiate between newlines and spaces.
# This doesn't do what it looks like it does.
for line in $(cat $1); do
echo $line
echo
done
for line in $(cat $1); do
echo $line
echo
done
# This, however, does.
while read line; do
echo $line
echo
done < $1
while read line; do
echo $line
echo
done < $1






Example 1
#!/bin/bash
# Altering IFS to only tokenise on newlines.
OFS=$IFS; IFS='
'
for LINE in $(cat ~/thefile ); do
echo LINE # or whatever
done
IFS=$OFS # reset back to original value
Example 2
#!/bin/bash
# Quoting your input
for LINE in "$(cat ~/thefile)"; do
echo "$LINE"
done