1

I have a file named newfile. The contents of this file are:

abc
xyz
abc

Now I want to find lines which start with a and end with c. I enter the following command but the results are not the same as expected by me:

grep -E   '^ac$' newfile

The problem with this command is that when I use ^ac$ the command interprets it as starting with ac instead of starting with a.

6

The problem with this command is that when I use ^ac$ the command interprets it as starting with 'ac' instead of starting with 'a'.

Not really. Since you used the $ anchor, you are searching for the lines which end right after the ac string, so only lines containing exactly single ac and no more characters are matched.

To allow any characters between those letters, use the regex for any count of any characters: .* (Or if you want to allow just one character like in abc in the example, use . without quantifiers like *.)

By the way, you can simply leave out the option -E for this regex, since it does not involve any syntax that would differ in these two variants.

So the result is:

grep '^a.*c$' newfile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.