2

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 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Note: The POSIX BRE standard doesn't specify support for alternation. Some implementations support it (with \|), but it's not actually part of the standard.
2

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")'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.