How to escape ] char in character class in sed

881 Views Asked by At

echo "eh]" | sed -r 's/[\]a]/lol/g' returns eh] instead of ehlol. no errors are raised so I assume \] is some kind of sed magic. Im tired of constant sed problems, but I have to use it. so how to escape ] in sed substition expression?

1

There are 1 best solutions below

1
On BEST ANSWER

You can simply use echo "eh]" | sed -r 's/[]a]/lol/g':

  • without the backslash
  • and ] as first character inside the brackets.

] and \ have some specialties when used inside brackets. Let me cite from the 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.