MLSC
MLSC

Reputation: 5972

Extracting string between brackets

How can I extract exact string between brackets?

What I tried is:

echo "test [test1] test" | grep -Po "(?=\[).*?(?=\])"

But the output is:

[test1

It should be:

test1

Better to use grep.

Upvotes: 2

Views: 6164

Answers (5)

Ed Morton
Ed Morton

Reputation: 203522

This will work with any version of sed as it's just a plain old BRE:

$ echo "test [test1] test" | sed 's/.*\[\(.*\)\].*/\1/'
test1

Upvotes: 1

konsolebox
konsolebox

Reputation: 75488

I'd prefer having negated ] to prevent greedy matching:

echo "test [test1] test [test2] xyz" | grep -Po "(?<=\[)[^\]]*(?=\])"

Output:

test1
test2

Upvotes: 3

Jotne
Jotne

Reputation: 41456

awk should do too:

echo "test [test1] test" | awk -F"[][]" '{print $2}'
test1

Or sed

echo "test [test1] test" | sed 's/[^[]*\[\|\].*//g'
test1

Upvotes: 4

Maroun
Maroun

Reputation: 95968

Another solution, worth mentioning:

echo "test [test1] test" | grep -Po '[^\[]+(?=[\]])'

In this case, the pattern A(?=B) means: Find A where expression B follows.

If you want the [ and ] you can try this:

echo "test [test1] test" | grep -Po '[\[].*[\]]'

Upvotes: 3

enrico.bacis
enrico.bacis

Reputation: 31494

Use a lookbehind:

echo "test [test1] test" | grep -Po "(?<=\[).*?(?=\])"

Upvotes: 8

Related Questions