如何替换所有出现的字符,如'[','('etc with'\ [','\('在文件中使用'sed'?

时间:2011-01-14 06:48:08

标签: shell scripting sed vim

我有一个文件“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”中使用substitue运算符,我可以获得相同的结果。 即。如果我在命令模式下的vi编辑器中使用:1,$ s/\[/\\[/g,我会看到所有[个字符都替换为\[

但是,如果我尝试使用sed命令在shell脚本中使用相同的substitue命令,我将无法获得相同的结果。 即如果我在shell脚本中使用以下命令,我无法实现所需的结果:

sed "s/\[/\\[/g"  $temp_file2 > $temp_file1
where $temp_file2 conatins the lines with '[' characters and $temp_file1 should contain the replaced '\[' chars

2 个答案:

答案 0 :(得分:1)

 sed 's/[][()]/\\&/g' infile > outfile

输出

$ sed 's/[][()]/\\&/g' infile
Capsule arr\[0\] in state A
rate_ul/dl=\(2000000/7000000\)
Capsule RBx\[0\] in state

答案 1 :(得分:0)

gawk版

gawk '{gsub(/[()\]\[]/,"\\\\&")}1' file