I'm searching through a file of people that is structured like below

John Smith 555-555-5555 Harvard Square, Boston

I'm interested in finding all the LAST names that start with the a certain letter. I've tried using "grep \


I suggest you use awk instead of grep e.g. to find lines whose second space-separated field starts with letter S

awk '$2 ~ /^S/' file

Try using grep with a Regex pattern:

grep -P "(?<=^[A-Za-z]+\\s)A"

This should match all entrys with the last name beginning with A.

Regex explanation

The Lookbehind (?<=text) checks whether text occurs before the actually searched pattern. I use it to skip the first name, which is given by ^[A-Za-z]+\\s, meaning beginning of line (^), then at least one letter, no matter if captital or not, then a space (\\s). After the lookbehind, the actually matched pattern stands, in this case the capital letter A.

  • Try grep -P "^[A-Za-z]+\\sA" instead. It might work without the lookbehind – s3lph Oct 11 '14 at 22:59
  • No still doesn't – Justin Oct 11 '14 at 23:39
  • Do you actually append the file name? – s3lph Oct 11 '14 at 23:40

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.