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

455 Views Asked by At

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?

2

There are 2 best solutions below

0
Wiktor Stribiżew On BEST ANSWER

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.

0
anubhava On

This can be done in bash itself without calling any external utility like awk or sed:

s="foo}bar]baz"
echo "${s//[]\}]/@}"

foo@bar@baz

Another option is tr:

tr '[]}]' '@' <<< "$s"

foo@bar@baz