Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape square brackets inside brackets in grep

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!

like image 475
Tiago Pimenta Avatar asked Mar 21 '23 15:03

Tiago Pimenta


1 Answers

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.

like image 89
Laurence Gonsalves Avatar answered Apr 24 '23 22:04

Laurence Gonsalves