I am trying to get a string that matches the following pattern: starts with foo and finishes with bar.
grep -e "^foo*bar$"
I am trying to get a string that matches the following pattern: starts with foo and finishes with bar.
grep -e "^foo*bar$"
There are three parts to the pattern you want to match:
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$.
o*will only match zero or moreocharacters - see How do regular expressions differ from wildcards used to filter files – steeldriver Mar 20 '19 at 00:36grep -e "^foo" -e "bar$" file. This variant works. – Bionix1441 Mar 20 '19 at 00:39^foo.*bar$. That's the point, with intenional pun. – Weijun Zhou Mar 20 '19 at 02:29bashbefore it is passed togrep, see https://mywiki.wooledge.org/Quotes – Sundeep Mar 20 '19 at 07:35