我正在尝试使用sed
,但我的模式包含[]
括号和斜杠 ( /
)。
我尝试过引用,但没有帮助。
我该如何逃避它?
例子:
$ sed -i'.bak' "s/^includes[] =/;includes[] =/g" *.make
sed: 1: "s/^includes[] =/;includ ...": unterminated substitute in regular expression
$ sed -i'.bak' 's/^includes[] = includes/;includes/g' *.make
sed: 1: "s@^includes[] = i ...": unbalanced brackets ([])
$ sed -i'.bak' 's/^includes[] = foo/includes//;includes[] = foo/includes//g' *.make
sed: 1: "s/^includes[] = foo/inc ...": bad flag in substitute command: '/'
答案1
要转义斜杠,您可以使用除正斜杠之外的任何字符来分隔正则表达式。
例如(foo1/
-> foo2/
):
sed "s@foo1/@foo2/@"
sed "s|foo1/|foo2/|"
要转义括号(这也适用于斜杠),您必须在定界字符之前放置一个反斜杠字符,从而使该字符按字面意思处理。
例如(foo[] =
-> ;foo[] =
):
sed "s/foo\[\] =/;foo\[\] =/"
通过运行man sed
(Sed 正则表达式)。