AlwaysLearning
AlwaysLearning

Reputation: 8051

Negating a closing square bracket

The following does not show any matches:

echo "A" | egrep '[^\]]'

If I put \[ instead of \], it works. So, how can I match a not a closing square bracket?

Upvotes: 1

Views: 557

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52506

In bracket expressions, you don't have to escape characters, so it's just

grep '[^]]'

You also don't need egrep/grep -E, there are no extended regular expressions involved.

Your other try,

grep '[^\[]'

worked because [ can be anywhere within a bracket expression, but ] must be the first character. Since you don't have to escape, the \ is actually literal, and the result would be "anything other than \ or [":

grep '[^\[]' <<< '\'

won't match. In summary, to include or exclude brackets, you don't have to escape them, and ] needs to be the first character:

grep '[[]'  # match opening bracket
grep '[^[]' # match anything but opening bracket
grep '[]]'  # match closing bracket
grep '[^]]' # match anything but closing bracket

and if more characters are involved, make sure to stick ] to the beginning:

grep '[]abc]'
grep '[^]abc]'

If you don't, as in

grep '[^a]bc]'

the expression will be interpreted as "anything but a followed by bc]"

Upvotes: 4

Related Questions