sed to match first pattern among multiple matches

526 Views Asked by At

So for a given text like

a[test] asdfasdf [sdfsdf]b

I want the first match of text which is inside the first square brackets (regex = [.*]), so in this case [test].

I tried the following command it didn't work:

echo "a[test] asdfasdf [sdfsdf]b" | sed -n -e 's/.*\(\[.*\]\).*/\1/p'

This is returning [sdfsdf]

How do I get [test] instead ?

1

There are 1 best solutions below

1
oguz ismail On BEST ANSWER

.* will select the longest match. Use [^[]* and [^]]* instead.

sed -n -e 's/[^[]*\(\[[^]]*\]\).*/\1/p'