6

Question: Why can't I escape the "]"?

$ printf "*#$@~\!&*()[]\n"
*#~\!&*()[]
$ printf "*#$@~\!&*()[]\n" | sed 's/[*#$@~!&*()\[\]]//g'
*#~\!&*()
$
0

1 Answer 1

8

Inside [...], backslash is not special. [\[] matches both backslash and [1.

If you want to include the ] character in the set, you have to make sure it's first: []X] matches ] or X while [X]] would match X followed by ] (and [X\]] would match X or \ followed by ]). To exclude it, it has to be right after ^: [^]X] is any character but ] or X.

So, in your example:

sed 's/[]*\#$@~!&*()[]//g'

1There are some exceptions to that with GNU sed when the POSIX conformance mode has not been enabled (via $POSIXLY_CORRECT or --posix) which is why, for compatibility with that implementation, when you do need backslash to be included in the set, it's better to write it as [\\].

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .