【问题标题】:How to replace all the occurences of chars like '[' , '(' etc with '\[' , '\(' using "sed" in a file?如何在文件中使用“sed”替换所有出现的字符,如 '[' , '(' 等 '\[' , '\(' ?
【发布时间】: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"

标签: shell scripting sed vim


【解决方案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

【讨论】:

  • 谢谢哥们!!可能使用双引号是对我不起作用的原因。
  • @Abhijeet 我将其优化为只有一个 sed 脚本
  • 我不知道。所以对我真的很有帮助。从现在开始我会这样做。谢谢!!
【解决方案2】:

gawk 版本

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

【讨论】:

  • 如果你使用/[][()]/,你不需要所有的转义符
猜你喜欢
  • 2023-03-15
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 2018-06-25
  • 1970-01-01
  • 2016-08-01
  • 2019-08-18
相关资源
最近更新 更多