如何使用bash在字符串中用"
替换\"
?
例如:
txt-File包含如下文字:
Banana "hallo" Apple "hey"
这必须转换为:
Banana \"hallo\" Apple \"hey\"
我试过
a=$(cat test.txt)
b=${a//\"/\"}}
但这不起作用。
这是如何运作的?
答案 0 :(得分:1)
string='Banana "hallo" Apple "hey"'
echo "$string"
Banana "hallo" Apple "hey"
string=${string//\"/\\\"} # Note both '\' need '"' need to be escaped.
echo "$string"
Banana \"hallo\" Apple \"hey\"
一个小解释
${var/pattern/replacement}
使用pattern
替换var
中replacement
的次次。
${var//pattern/replacement}
使用pattern
替换var
中replacement
的所有次出现。
如果模式或替换包含shell中具有特殊含义的"
或/
等字符,则需要对其进行转义以使shell将其视为文字。