How to escape square brackets inside brackets in grep

escaping, grep, regex, regex-negation

Solution

Place the `]` immediately after the `^`.

Here's an example. Input file "foo" contains:

foo
[
bar
]
baz
quux

We execute the command:

grep '[^][]' foo

The output is:

foo
bar
baz
quux

From the documentation on bracket expressions in POSIX regular expressions:

The right-bracket ( ']' ) shall lose its special meaning and represent itself in a bracket expression if it occurs first in the list (after an initial circumflex ( '^' ), if any).

and also:

The special characters '.', '*', '[', and '\' (period, asterisk, left-bracket, and backslash, respectively) shall lose their special meaning within a bracket expression.

Problem

I want to match the other than square brackets characters in regular expression. Precisely I want to match some special characters and some others don't, thus I want to specify them ``` # grep $'[^a-zA-Z0-9#\\/:!<>{},=?. ()["_+;*\'&|$-]' file ``` This is missing a `]`, I have tried escaping with `\]`, `\\]` and so on, I read people doing that outer the `[^]`, but I need it inside!

Original source