如何替换 bash 中的反斜杠和单引号模式?

How to replace backslash and single quote pattern in bash?

我想用 \'

替换下面的模式 \\'

所以这样的文字:

ABC DEF \\'S XYZ

会变成:

ABC DEF \'S XYZ

我试过这样使用 sed:

sed "s/\\\\\'/\\\'/g"

但它并没有取代任何东西。有什么想法吗?

试试这个:

echo "ABC DEF \\'S XYZ" | sed -r 's/\+/\/g'

输出:ABC DEF \'S XYZ

此处 -r 开关 sed 用于扩展正则表达式。 sed 将在整行中匹配一次或多次出现的 \ (\+),并将匹配项替换为 \ (\).

这个有效:

echo ABC DEF \\'S XYZ | sed -r 's/(.*)\\\(.*)/ \/g'

根据使用单引号或双引号,有不同的方法:

$ cat a
hello \\' aaa
afa

单引号 - 需要关闭并再次打开以插入单引号:

$ sed 's#\\\\'"'"'#X'"'"'#g' a
hello X' aaa
afa

双引号-每个\需要转义三次:

$ sed "s#\\\\\\\\'#\\'#g" a
hello \' aaa
afa

好读:Remove backslashes from a text file

  1. In a shell (like bash) you can escape backslash by backslash. So instead of \ write \. Enclosing the string between double quotes " makes backslash behaviour more complicated<1> but double backslash will still produce a single backslash. Enclosing the string between single quotes ' makes every character to be treated literally except '.