bash read loop only reading first line of input variable

ぐ巨炮叔叔 提交于 2019-12-23 23:02:15

问题


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?


回答1:


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"



回答2:


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.



来源:https://stackoverflow.com/questions/21227505/bash-read-loop-only-reading-first-line-of-input-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!