regexsedescapingcharacter-class

How to escape closing square bracket within regular expression character class?


This command works as expected:

$ echo "foo}bar]baz" | sed 's/}/@/g; s/]/@/g'
foo@bar@baz

Now I am trying to do the same thing using character class like this:

$ echo "foo}bar]baz" | sed 's/[}\]]/@/g'
foo}bar]baz

This did not work. I want to have a character class with two characters } and ] so I thought escaping the square bracket like }\] would work but it did not.

What am I missing?


Solution

  • You may use "smart" placement:

    echo "foo}bar]baz" | sed 's/[]}]/@/g'
    

    See the online sed demo

    Here, the ] char must appear right after the open square bracket, otherwise, it is treated as the bracket expression close bracket and the bracket expression is closed prematurely.

    Note that in case you want to safely use - inside a bracket expression, you may use it right before the close square bracket.