Question

I have a read loop that is reading a variable but not behaving the way I expect. I want to read every line of my variable and process each one. Here is my loop:

while read -r line
do
   echo $line | sed 's/<\/td>/<\/td>$/g' | cut -d'$' -f2,3,4 >> file.txt
done <<< "$TABLE"

I expect it to process every line of the file but instead it just does the first one. If my the middle is simply echo $line >> file.txt it works as expected. What's going on here? How do I get the behavior I want?

Was it helpful?

Solution

It seems your lines are delimited by \r instead of \n.

Use this while loop to iterate the input with use of read -d $'\r':

while read -rd $'\r' line; do
    echo "$line" | sed 's~</td>~</td>$~g' | cut -d'$' -f2,3,4 >> file.txt
done <<< "$TABLE"

OTHER TIPS

If $TABLE contains a multi-line string, I recommend

printf '%s\n' "$TABLE" |
while read -r line; do
   echo $line | sed 's/<\/td>/<\/td>$/g' | cut -d'$' -f2,3,4 >> file.txt
done

This is also more portable since the '<<<' operator for here-strings is not POSIX.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top