我需要一个正则表达式来匹配 any character(s) followed by foo. or bar. followed by anything followed by is.a.server followed by anything
。
例如:
"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
我有一个变量 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"
具有多个 grep
的上述命令效果很好,输出:
foo.lnx station is.a.server
my bar.unx node is.a.server.and.client
foo.l is.a.server.linux
我正在寻找一个正则表达式(单个 grep
),如下所示:
$ 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.*"
答案 0 :(得分:2)
假设 GNU grep
。
使用 POSIX ERE,-E
选项,不要转义管道:
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"
或者,使用 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"
结果:
foo.lnx station is.a.server
my bar.unx node is.a.server.and.client
foo.l is.a.server.linux
答案 1 :(得分:2)
如果你有 grep 可用,那么你也有 awk 可用。在每个 Unix 机器上的任何 shell 中使用任何 awk:
awk '/(foo|bar)\..*is\.a\.server/' file
或者如果 regexp 的一部分必须来自 shell 变量,则:
match_for='foo|bar'
awk -v mf="$match_for" '$0 ~ (mf"\\..*is\\.a\\.server")'