如何grep以指定字符串开头并以另一个指定字符串结尾的行?

时间:2021-02-21 08:56:04

For example how would I get lines that begin with foo and end with bar?

例如,我如何得到以foo开头并以bar结尾的行?

Example lines:

foo12345abar
fooabcdbar
fooy7ghqqbar

This does not seem to work

这似乎不起作用

grep '^foo[.]*bar$'

What is the correct regex?

什么是正确的正则表达式?

2 个解决方案

#1


2  

The reason your expression does not work is because [.] represents a dot, literally. Your expression would match strings that look like this:

你的表达式不起作用的原因是因为[。]代表一个点,字面意思。您的表达式将匹配如下所示的字符串:

foo.......bar
foo...bar
boobar

To make it work remove square brackets [] around the dot meta-character:

要使其工作,请删除点元字符周围的方括号[]:

^foo.*bar$

Demo.

#2


0  

^foo.*?bar$

Here is the working DEMO.

这是工作DEMO。

#1


2  

The reason your expression does not work is because [.] represents a dot, literally. Your expression would match strings that look like this:

你的表达式不起作用的原因是因为[。]代表一个点,字面意思。您的表达式将匹配如下所示的字符串:

foo.......bar
foo...bar
boobar

To make it work remove square brackets [] around the dot meta-character:

要使其工作,请删除点元字符周围的方括号[]:

^foo.*bar$

Demo.

#2


0  

^foo.*?bar$

Here is the working DEMO.

这是工作DEMO。