用给定的字符串替换行的子字符串

时间:2019-02-01 15:56:21

标签: bash

我正在尝试使用其他名称替换名称,该名称可以正常工作,但是当我使用“ []”时,它将无法正常工作。

#!/bin/bash
firstString="I love [Candy] Store"
firstChange="[Candy] Store"
secondString="Chocolate Store"
echo "${firstString//$firstChange/$secondString}"

我期望:

"I love Chocolate Store".

工作示例:

#!/bin/bash
firstString="I love Candy Store"
firstChange="Candy Store"
secondString="Chocolate Store"
echo "${firstString//$firstChange/$secondString}"

输出:

I love Chocolate Store.

我正在尝试使其适用于两种情况。

有人可以帮我吗?

谢谢

1 个答案:

答案 0 :(得分:0)

嗯,这可行:

#!/bin/bash
firstString="I love [Candy] Store"
firstChange="\[Candy\] Store"
secondString="Chocolate Store"
echo "${firstString//$firstChange/$secondString}"

这可能对您没有太大帮助;如果您的“更改”字符串是从某个地方输入的,那么您就不能指望它是否已正确转义。

问题在于bash扩展将firstChange值视为模式而不是常规字符串。

根据此答案https://stackoverflow.com/a/2856010/200136,printf“%q”是解决方案:

#!/bin/bash
firstString="I love [Candy] Store"
firstChange="[Candy] Store"
printf -v quoteChange "%q\n" $firstChange
safeChange=$(echo $quoteChange)
secondString="Chocolate Store"
echo "${firstString//$safeChange/$secondString}"
相关问题