-1

I am trying to get a string that matches the following pattern: starts with foo and finishes with bar.

grep -e "^foo*bar$"

1 Answers1

5

There are three parts to the pattern you want to match:

  • The first one is to start the string with 'foo'. So, use a start anchor: '^foo'.
  • The second one is to end the string with 'bar'. Here, use an end anchor: 'bar$'.
  • The third part is what comes in between the start and end anchors. In your case, you want to match all of the characters zero or more times (i.e. there may or may not be characters in between). This is represented by the expression '.*'. The dot matches any character, and the asterisk quantifier specifies that it may be matched zero or more times.

Putting all of this together, you'll get the expression:

grep '^foo.*bar$' file

As an example, consider this test file:

$ cat testfile
foobar
foo bar
foo 123 bar
123 foo bar
foo bar 123
123 foo bar 123

Now running the grep command:

$ grep '^foo.*bar$' testfile
foobar
foo bar
foo 123 bar

Note that the variant you have specified in the comments (grep -e "^foo" -e "bar$" file) behaves differently:

$ grep -e "^foo" -e "bar$" testfile
foobar
foo bar
foo 123 bar
123 foo bar
foo bar 123

This is because the -e options are combined with an OR operation. In addition to the original ^foo.*bar$ results, you will also get results matching ^foo as well as results matching bar$.

Haxiel
  • 8,361