Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting string between brackets

Tags:

grep

bash

sed

awk

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.

like image 938
MLSC Avatar asked Jun 13 '26 10:06

MLSC


2 Answers

Use a lookbehind:

echo "test [test1] test" | grep -Po "(?<=\[).*?(?=\])"
like image 186
enrico.bacis Avatar answered Jun 15 '26 03:06

enrico.bacis


awk should do too:

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

Or sed

echo "test [test1] test" | sed 's/[^[]*\[\|\].*//g'
test1
like image 28
Jotne Avatar answered Jun 15 '26 03:06

Jotne