如何使用 sed 将 \' 替换为 ''

how to replace a \' with '' using sed

我有一个这样的文件test.sql:

'here is' and \' other for 'you'

并想用 ''(2 个单引号)替换 postgres 的 \'(转义单引号),并单独保留其他单引号。我该怎么做。我试过:

Mon Mar 16$ sed -i.bak s/\'/''/g test.sql 

但这去掉了所有的单引号。

你的敌人是 shell 引用。字符串

s/\'/''/g

在被提供给 sed 之前被 shell 破坏了。对于shell,''是一个空字符串,而\'抑制了单引号的这种特殊含义(这样引号就是一个真正的单引号字符)。 sed 处理后看到的是

s/'//g

...只是删除所有单引号。

有多种方法可以解决此问题;其中之一是

sed -i.bak "s/\\'/''/g" test.sql

双引号shell字符串中,反斜杠需要转义(有例外)。这意味着 shell 命令中的 "s/\\'/''/g" 转换为 s/\'/''/g 作为 sed 的参数。在 sed 正则表达式中,反斜杠也需要转义,所以这实际上是我们想要发生的事情:\' 的所有实例都将替换为 ''

sed "s/[\]'/''/g" test.sql
# also work but may depend on shell
sed "s/[\]'/''/g" test.sql

与 Wintermute 相同的想法,但使用 class 来避免 shell 的多次转义,而不是双引号中的 sed