如何在字符串中扩展bash变量并保留换行符 [英] How to expand bash variable in a string and preserve newline

查看:49
本文介绍了如何在字符串中扩展bash变量并保留换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此选项适用于单行字符串:

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[*]}"

如何保留换行符?

推荐答案

即使我无法完全理解您的目标,
正确引用会保留新行.

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

更改这两行:

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

这篇关于如何在字符串中扩展bash变量并保留换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆