1

I have a few grep expressions that aren't working as I intended and I cannot figure out as to why.

The first expression is to find lines that start and end with the same character. This is the expression I am using...

grep -E '(.).*\1$' input

The second expression is very similar as it is to find lines that have the same 2nd character and second to last character...

grep -E '(.)(.).*\2.$' input

The last expression is to find lines with only a single word and end with a punctuation...

grep -E '(\w){1}.*[[:punct:]]$' input

I don't understand why these are not working, am i doing something terribly wrong or just a simple mistake?

4

You left off the start-of-line anchor (caret symbol). Here are modified commands which only match entire lines (and won't match substrings):

grep -E '^(.).*\1$' input

grep -E '^(.)(.).*\2.$' input

grep -E '^(\w){1}.*[[:punct:]]$' input

You'll probably also want to modify your second and third commands.

The second command doesn't require two capture groups. You can do it with just one:

grep -E '^.(.).*\1.$' input

The third command is incorrect: it will match strings with multiple words. A corrected version might be:

grep -E '^\w+[[:punct:]]$' input

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.