Question: Why can't I escape the "]"?
$ printf "*#$@~\!&*()[]\n"
*#~\!&*()[]
$ printf "*#$@~\!&*()[]\n" | sed 's/[*#$@~!&*()\[\]]//g'
*#~\!&*()
$
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityInside [...]
, 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 [\\]
.