grep: regex only for match anything between parenthesis
Here are a few options, all of which print the desired output:
Using
grep
with the-o
flag (only print matching part of line) and Perl compatible regular expressions (-P
) that can do lookarounds:printf "this is (test.com)\n" | grep -Po '(?<=\().*(?=\))'
That regex might need some explaining:
(?<=\()
: This is a positive lookbehind, the general format is(?<=foo)bar
and that will match all cases ofbar
found right afterfoo
. In this case, we are looking for an opening parenthesis, so we use\(
to escape it.(?=\))
: This is a positive lookahead and simply matches the closing parenthesis.
The
-o
option togrep
causes it to only print the matched part of any line, so we look for whatever is in parentheses and then delete them withsed
:printf "this is (test.com)\n" | grep -o '(.*)' | sed 's/[()]//g'
Parse the whole thing with Perl:
printf "this is (test.com)\n" | perl -pe 's/.*\((.+?)\)/$1/'
Parse the whole thing with
sed
:printf "this is (test.com)\n" | sed 's/.*(\(.*\))/\1/'
One approach would be to use PCRE - Perl Compatible Regular Expressions with grep
:
$ echo "this is (test.com)" | grep -oP '(?<=\().*(?=\))'
test.com
References
- regular-expressions.info - lookarounds