Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 949
Lone Learner Avatar asked Sep 12 '25 00:09

Lone Learner


1 Answers

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.

like image 124
Wiktor Stribiżew Avatar answered Sep 13 '25 15:09

Wiktor Stribiżew