如何在 sed 中转义字符 class 中的 ] char

How to escape ] char in character class in sed

echo "eh]" | sed -r 's/[\]a]/lol/g' returns eh] 而不是 ehlol。没有错误出现,所以我认为 \] 是某种 sed 魔法。我厌倦了不断的 sed 问题,但我必须使用它。那么如何在 sed 替换表达式中转义 ]?

您可以简单地使用 echo "eh]" | sed -r 's/[]a]/lol/g':

  • 没有反斜杠
  • ] 作为括号内的第一个字符。

]\ 在括号内使用时有一些特点。 让我引用 documentation:

A leading ^ reverses the meaning of list, so that it matches any single character not in list. To include ] in the list, make it the first character (after the ^ if needed), to include - in the list, make it the first or last; to include ^ put it after the first character.

The characters $, *, ., [, and \ are normally not special within list. For example, [\*] matches either ‘\’ or ‘*’, because the \ is not special here. However, strings like [.ch.], [=a=], and [:space:] are special within list and represent collating symbols, equivalence classes, and character classes, respectively, and [ is therefore special within list when it is followed by ., =, or :. Also, when not in POSIXLY_CORRECT mode, special escapes like \n and \t are recognized within list. See Escapes.