在字符串中替换“by \”

时间:2016-12-15 14:25:04

标签: string bash replace

如何使用bash在字符串中用"替换\"

例如:

txt-File包含如下文字:

Banana "hallo" Apple "hey"

这必须转换为:

Banana \"hallo\" Apple \"hey\"

我试过

a=$(cat test.txt)
b=${a//\"/\"}}

但这不起作用。

这是如何运作的?

1 个答案:

答案 0 :(得分:1)

使用[ parameter expansion ]

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替换varreplacement次。

${var//pattern/replacement}

使用pattern替换varreplacement的所有次出现。

如果模式或替换包含shell中具有特殊含义的"/等字符,则需要对其进行转义以使shell将其视为文字。