如何在包含“”的字符串中插入变量?

sup*_*rio 38 shell bash xml variable

我想通过插入变量来构造一个 xml 字符串:

str1="Hello"
str2="world"

xml='<?xml version="1.0" encoding="iso-8859-1"?><tag1>$str1</tag1><tag2>$str2</tag2>'

echo $xml
Run Code Online (Sandbox Code Playgroud)

结果应该是

<?xml version="1.0" encoding="iso-8859-1"?><tag1>Hello</tag1><tag2>world</tag2>
Run Code Online (Sandbox Code Playgroud)

但我得到的是:

<?xml version="1.0" encoding="iso-8859-1"?><tag1>$str1</tag1><tag2>$str2</tag2>
Run Code Online (Sandbox Code Playgroud)

我也试过

xml="<?xml version="1.0" encoding="iso-8859-1"?><tag1>$str1</tag1><tag2>$str2</tag2>"
Run Code Online (Sandbox Code Playgroud)

但这会删除内部双引号并给出:

<?xml version=1.0 encoding=iso-8859-1?><tag1>hello</tag1><tag2>world</tag2>
Run Code Online (Sandbox Code Playgroud)

jan*_*nos 37

您只能在双引号字符串中嵌入变量。

使这项工作的一种简单而安全的方法是像这样打破单引号字符串:

xml='<?xml version="1.0" encoding="iso-8859-1"?><tag1>'"$str1"'</tag1><tag2>'"$str2"'</tag2>'
Run Code Online (Sandbox Code Playgroud)

请注意,在脱离单引号字符串后,我将变量括在双引号中。这是为了确保在变量中包含特殊字符是安全的。

由于您要求另一种方式,这是使用printf以下的劣质替代方案:

xml=$(printf '<?xml version="1.0" encoding="iso-8859-1"?><tag1>%s</tag1><tag2>%s</tag2>' "$str1" "$str2")
Run Code Online (Sandbox Code Playgroud)

这是劣质的,因为它使用了一个子外壳来实现相同的效果,这是一个不必要的额外过程。

正如@steeldriver在评论中所写,在现代版本的 bash 中,您可以这样编写以避免子 shell:

printf -v xml ' ... ' "$str1" "$str2"
Run Code Online (Sandbox Code Playgroud)

由于printf是内置的 shell,因此这个替代方案可能与我在顶部的第一个建议有关。


Sid*_*med 10

单引号字符串中不会发生变量扩展。

您可以对字符串使用双引号,并使用\. 像这样 :

xml="<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><tag1>$str1</tag1><tag2>$str2</tag2>"
Run Code Online (Sandbox Code Playgroud)

结果输出:

<?xml version="1.0" encoding="iso-8859-1"?><tag1>hello</tag1><tag2>world</tag2>
Run Code Online (Sandbox Code Playgroud)