Reputation: 5972
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
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
Reputation: 75488
I'd prefer having negated ]
to prevent greedy matching:
echo "test [test1] test [test2] xyz" | grep -Po "(?<=\[)[^\]]*(?=\])"
Output:
test1
test2
Upvotes: 3
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
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
Reputation: 31494
Use a lookbehind:
echo "test [test1] test" | grep -Po "(?<=\[).*?(?=\])"
Upvotes: 8