regex to match one of the multiple strings followed by another string

Viewed 79

I need a regex to match any character(s) followed by foo. or bar. followed by anything followed by is.a.server followed by anything.

e.g:

"foo.lnx station is.a.server" # match this
"my bar.unx node is.a.server.and.client" # match this
"baz station is.a.server" # do NOT not match this
"foo.lnx station not.a.server" # do NOT not match this, b'cos it don't match "is.a.server"
"foo.l is.a.server.linux" # match this

I have a variable match_for="foo\|bar"

$ echo "foo.lnx station is.a.server
my bar.unx node is.a.server.and.client
baz station is.a.server
foo.lnx station not.a.server
foo.l is.a.server.linux" | grep "$match_for\\." | grep "is\.a\.server"

Above command with multiple grep works good, outputs:

foo.lnx station is.a.server
my bar.unx node is.a.server.and.client
foo.l is.a.server.linux

I am looking for a single regex (single grep) as below:

$ echo "foo.lnx station is.a.server
> my bar.unx node is.a.server.and.client
> baz station is.a.server
> foo.lnx station not.a.server
> foo.l is.a.server.linux" | grep "($match_for)\..*is\.a\.server.*"
2 Answers

Assuming GNU grep.

Use POSIX ERE, -E option, do not escape pipe:

match_for='foo|bar'
echo "foo.lnx station is.a.server
my bar.unx node is.a.server.and.client
baz station is.a.server
foo.lnx station not.a.server
foo.l is.a.server.linux" | grep -E "($match_for)\..*is\.a\.server"

Or, with POSIX BRE:

match_for='foo\|bar'
echo "foo.lnx station is.a.server
my bar.unx node is.a.server.and.client
baz station is.a.server
foo.lnx station not.a.server
foo.l is.a.server.linux" | grep "\($match_for\)\..*is\.a\.server"

Results:

foo.lnx station is.a.server
my bar.unx node is.a.server.and.client
foo.l is.a.server.linux

If you have grep available then you also have awk available. Using any awk in any shell on every Unix box:

awk '/(foo|bar)\..*is\.a\.server/' file

or if part of the regexp has to be from a shell variable then:

match_for='foo|bar'
awk -v mf="$match_for" '$0 ~ (mf"\\..*is\\.a\\.server")'
Related