How to expand bash variable in a string and preserve newline

為{幸葍}努か 提交于 2019-12-08 10:00:20

问题


This one works for single line string:

var2="2018"
str="${var1:-hello} world! 
Happy $var2 new year $var2"

newstr=()
for cnt in "$str" ;do
    echo "$cnt"
    [ "${cnt:0:1}" == '$' ] && cnt=${cnt:1} && cnt=${!cnt}
    newstr+=($cnt)
done
newstr="${newstr[*]}"

How to preserve the newline?


回答1:


Even if I fail to fully understand what your goal is,
correctly quoting will preserve the new lines.

Change this two lines:

[ "${cnt:0:1}" == '$' ] && cnt="${cnt:1}" && cnt="${!cnt}"
newstr+=("$cnt")



回答2:


The purpose of the script is obscure to me, but here is the way I would write it to read line by line:

var2="2018"
str="${var1:-hello} world! 
Happy $var2 new year $var2"

newstr=()
while read cnt; do
    echo "$cnt"
    [ "${cnt:0:1}" == '$' ] && cnt=${cnt:1} && cnt=${!cnt}
    newstr+=($cnt)
done < <(echo "$str")
newstr="${newstr[*]}"

The read command reads one line after the other. The natural way to write it would be with a pipe:

var2="2018"
str="${var1:-hello} world! 
Happy $var2 new year $var2"

newstr=()
echo "$str" | while read cnt; do
    echo "$cnt"
    [ "${cnt:0:1}" == '$' ] && cnt=${cnt:1} && cnt=${!cnt}
    newstr+=($cnt)
done
newstr="${newstr[*]}"

However the pipe creates a subshell and the variables modified inside the while loop would be discarded once stepping out of it, here especially the newstr variable.



来源:https://stackoverflow.com/questions/39739673/how-to-expand-bash-variable-in-a-string-and-preserve-newline

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