Nelson
Nelson

Reputation: 3232

How to grep lines that begin with a specified string and end with another specified string?

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

Example lines:

foo12345abar
fooabcdbar
fooy7ghqqbar

This does not seem to work

grep '^foo[.]*bar$'

What is the correct regex?

Upvotes: 1

Views: 48

Answers (2)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

^foo.*?bar$

Here is the working DEMO.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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.

Upvotes: 2

Related Questions