【发布时间】:2011-12-25 15:05:49
【问题描述】:
如何将单引号 (') 替换为反斜杠,然后使用 sed 替换单引号 (\')?
sed s/\'/\\\'/
不会工作,因为你永远不会写文字。
sed ":a;N;s/\'/\\'/g" <file1 >file2
不起作用,因为反斜杠将不再转义引号,它被视为正则表达式引号。
【问题讨论】:
-
适用于 Mac OS - 您的里程可能会有所不同...
如何将单引号 (') 替换为反斜杠,然后使用 sed 替换单引号 (\')?
sed s/\'/\\\'/
不会工作,因为你永远不会写文字。
sed ":a;N;s/\'/\\'/g" <file1 >file2
不起作用,因为反斜杠将不再转义引号,它被视为正则表达式引号。
【问题讨论】:
怎么样: sed "s,',BBBB',g" 文件 其中 B 是一个反斜杠 ... 即 4 个反斜杠 ...
【讨论】:
使用 -e 选项。
sed -e s/\'/\\'/g file2
【讨论】:
尝试以下方法:
sed -e s/\'/\\\\\'/g input > output
为了证明这是有效的:
echo "Hello 'World'" | sed -e s/\'/\\\\\'/g
输出应该是:
Hello \'World\'
【讨论】:
只需引用替换
$ echo \' | sed s/\'/"\\\'"/
$ \'
例如
$ cat text1
this is a string, it has quotes, that's its quality
$ sed s/\'/"\\\'"/ text1 > text2
$ cat text2
this is a string, it has quotes, that\'s its quality
【讨论】:
sed s/"\\\'"/\'/g
这似乎有效:
<<<"''''" sed 's/'\''/\\&/;s/\('"'"'\)\(..\)$/\\\1\2/;'s/\'\'$/\\\\\'\'/";s/'$/\\\'/"
\'\'\'\'
这显示了 4 种不同的方式,其中可以使用 sed 将单引号替换为反斜杠后跟单引号。
<<<\' sed 's/'\''/\\&/'<<<\' sed 's/\('"'"'\)/\\\1/'<<<\' sed s/\'/\\\\\'/<<<\' sed "s/'/\\\'/"将它们完全替换为上述正则表达式的四个单引号即可达到预期的效果。
【讨论】: