Sed

如何在 sed 中轉義不平衡的括號或斜線?

  • November 5, 2014

我正在嘗試使用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: '/'

要轉義斜杠,您可以使用正斜杠以外的任何字元來分隔正則表達式。

例如(foo1/-> foo2/):

sed "s@foo1/@foo2/@"
sed "s|foo1/|foo2/|"

要轉義括號(這也適用於斜杠),您必須在定界字元之前放置一個反斜杠字元,以使字元被逐字處理。

例如(foo[] =-> ;foo[] =):

sed "s/foo\[\] =/;foo\[\] =/"

通過執行man sedSed 正則表達式)閱讀更多內容。

引用自:https://unix.stackexchange.com/questions/165995