【发布时间】:2011-06-08 23:39:50
【问题描述】:
我有一个文件“say file.txt”,内容如下:
Capsule arr[0] in state A
rate_ul/dl=(2000000/7000000)
Capsule RBx[0] in state
...
...
使用 sed 运算符如何将所有出现的 [ 替换为 \[、( 与 \(、] 与 \] 等等。
Capsule arr\[0\] in state A
rate_ul/dl=\(2000000/7000000\)
Capsule RBx\[0\] in state
...
...
使用“gvim”中的替换运算符,我可以得到相同的结果。
IE。如果我在命令模式下的 vi 编辑器中使用:1,$ s/\[/\\[/g,我会看到所有[ 字符都替换为\[。
但是,如果我尝试使用 sed 命令在 shell 脚本中使用相同的替代命令,我将无法获得相同的结果。 即,如果我在 shell 脚本中使用以下命令,我将无法达到预期的效果:
sed "s/\[/\\[/g" $temp_file2 > $temp_file1
where $temp_file2 conatins the lines with '[' characters and $temp_file1 should contain the replaced '\[' chars
【问题讨论】:
-
在双引号内,您需要转义反斜杠:
sed "s/\[/\\\\[/g"