How do I search for a sequence of non-brackets with grep?

33 Views Asked by At

I have a file called test with this single line:

[word space](test words)

when I grep -ho "[^a]*" test, looking for sequences of non-a characters I get

[word sp
ce](test words)

which is exactly what I expect.

But when I grep -ho "[^\]]*" test, trying to search for sequences of non-closing-bracket characters, I get

[
w
o
r
d

s
p
a
c
e]
(
t
e
s
t

w
o
r
d
s
)

instead of the expected

[word space
(test words)

I have no idea what's causing this. Why is it matching bracket characters? Why is every character on its own line? Why is it so different from grep -ho "[^a]*" test? I thought \] would look for a literal ], and that's indeed what it seems when I do a grep -ho '\]' test. I'm completely lost.

EDIT AND SOLUTION:

Turns out my mistake was assuming I had to escape the bracket in the group. A simple grep -ho "[^]]*" test solves this.

0

There are 0 best solutions below