查找并替换为Tcl命令args符号的sed命令

时间:2013-02-01 12:27:43

标签: regex sed replace

我正在尝试使用tcl

替换包含sed命令分隔符'[''的文件中的字符串

示例:

string [$HelloWorld]必须由$HelloWord替换。请注意,它没有括号,要修改的文件是TCL文件。我如何使用sed命令执行此操作?

我试过了:

sed -i 's@[$HelloWorld]@$HelloWorld@g' <file_path>

1 个答案:

答案 0 :(得分:4)

您需要转义[],因为它们在regexp中被解释为字符类,而不是文字方括号:

$ sed 's/\[$HelloWorld\]/$HelloWorld/g' file
string $HelloWord

您可以在此处使用捕获组:

$ sed 's/\[\($HelloWorld\)\]/\1/g' file
string $HelloWord

如果要从文件中删除所有方括号,请使用sed 's/[][]//g'

# First check changes are correct
$ sed 's/[][]//g' file
string $HelloWorld

# Store the change back to the file 
$ sed -i 's/[][]//g' file

# Store changes back to the file and create back up of the original 
$ sed -i.bak 's/[][]//g' file
相关问题