I have a task that I need to find in the contents of a file the lines containing first and last name that both start with the same letter. Everything I have tried only searches for the first letter in the first name or just doesn't output anything. Can I get some guidance on where to go on this?

Data that needed to be parsed:

Frank Smith
Jim Jones
William Tuft
Jill Johnston
Fred White
Sue Cream
Barbara Bennett
Jeff Gordo

I figured it out using this egrep command:

egrep '(J[a-z]+ J)' addresses.txt

*for privacy reasons, I removed the addresses

  • 2
    Can you give an example? Post it in th quetion, not in tha comments. Sep 24, 2019 at 14:39
  • 4
    We cannot help you parse data you don't show. Please edit your question and include i) a few lines of your input file and ii) the output you would want from that file. Human names are notoriously difficult to parse though. Consider Jorge Francisco Isidoro Luis Borges Acevedo or Xi Jinping or John Henry Batterdown-Hatchingson. What's the last name there?
    – terdon
    Sep 24, 2019 at 14:39

3 Answers 3

$ grep -E '^[[:space:]]*([[:alpha:]])[[:alpha:]]*[[:space:]]+\1' yourfile.txt

The grep command will search yourfile.txt for:

  1. Any number of space characters (* means 0 or more) in the beginning of line, followed by
  2. Exactly one alphabetic character, followed by
  3. Any number of alphabetic characters (* means 0 or more), followed by
  4. At least one space character (+ means 1 or more), followed by
  5. The character matched in step 2. Here \1 is a back-reference to the actual string matched by the first parenthesized exression.

Note: The following command (using basic instead of extended regular expression) has the same effect as the one given above:

$ grep '^[[:space:]]*\([[:alpha:]]\)[[:alpha:]]*[[:space:]]\+\1' yourfile.txt
  • Backreferences are not defined in the extended regular expression standard (although I think that most implementations support it anyhow). So BRE is preferred.
    – Philippos
    Sep 25, 2019 at 9:00

Assuming a list of names:

$ cat file
George Washington
Ronald Reagan
Barack Obama
Donald Trump

$ awk 'substr($1,1,1) == substr($NF,1,1)' file
Ronald Reagan

As I use $NF (= the last field) for last name, it will work well if you have middle names, but it will fail miserably if you have a suffix like Jr. or a prefix like Mr. or Dr..

egrep '(J[a-z]+ J)' file.txt


Jim Jones

Jill Johnston

  • 1
    except that this obviously hard-codes the letter "J", missing "Barbara Bennett"; you'd have to repeat this for every other letter to have a general answer.
    – Jeff Schaller
    Sep 24, 2019 at 19:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .