问题
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