转义未转义的正斜杠

Mer*_*rig 0 sed regular-expression

我有包含转义和未转义正斜杠的字符串。

我正在寻找 sed 替换来仅转义未转义的斜杠,但似乎不支持负向后查找。

例子:

input: "https:\/\/github.com\/foo\/bar\/pull\/2934) is live at https://baz/test.com"

desired output: "https:\/\/github.com\/foo\/bar\/pull\/2934) is live at https:\/\/baz\/test.com"
Run Code Online (Sandbox Code Playgroud)

Kus*_*nda 5

sed默认情况下使用POSIX 基本正则表达式,其中不包括通常在 Perl 兼容正则表达式语言中找到的先行和其他零宽度断言。

相反,只需取消转义转义的斜杠,然后转义修改后的字符串中的所有斜杠:

sed -e 's@\\/@/@g' -e 's@/@\\/@g'
Run Code Online (Sandbox Code Playgroud)

这首先将所有实例更改\//,然后全部/更改为\/。这@是替换命令的替代分隔符,以避免牙签倾斜综合症(您几乎可以使用任何其他字符)。

例子:

$ echo '"https:\/\/github.com\/foo\/bar\/pull\/2934) is live at https://baz/test.com"' | sed -e 's@\\/@/@g' -e 's@/@\\/@g'
"https:\/\/github.com\/foo\/bar\/pull\/2934) is live at https:\/\/baz\/test.com"
Run Code Online (Sandbox Code Playgroud)

如果文本行存储在bashshell 中的字符串中,您可以在那里执行类似的操作:

$ string='"https:\/\/github.com\/foo\/bar\/pull\/2934) is live at https://baz/test.com"'
$ string=${string//\\\///}   # leaning toothpick warning!
$ string=${string//\//\\/}
$ printf '%s\n' "$string"
"https:\/\/github.com\/foo\/bar\/pull\/2934) is live at https:\/\/baz\/test.com"
Run Code Online (Sandbox Code Playgroud)

上面使用${variable//pattern/replacement}变量替换将patternin的所有匹配项替换$variablereplacement