Egrep with exact words

Hi, I have the following data in a file

bob
bobby
sam
sammy
ed
eddie

I need to grep these exact words: "bob", "sam", "ed". I don't want to see "bobby", "sammy", "eddie".

egrep 'bob|sam|ed'

gives me everything because egrep interprets these as a pattern. How can I specify an exact word?

Thanks everyone.

Use -w option:-

egrep -w "bob|sam|ed" filename

also, try using double quotes instead of single quotes for search expression. It can make a difference depending on OS, UX flavor.

Note that the -w option is not in the standards and is not present on all systems. And since you have one word per line in your input file it is easy to match what you want even when the -w option is not available. The standards also say that egrep is obsolete and need not be available on conforming implementations. If you're writing new code, I'd suggest either:

grep -E '^(bob|sam|ed)$' file

or

grep -E '^bob$|^sam$|^ed$' file

even though I don't know of any implementation that doesn't still treat egrep as a synonym for grep -E .

As far as using single quotes or double quotes goes; either will produce the same results for these words. I use single quotes here because there is no need for the shell to perform the extra expansions that double quotes require; so single quotes are slightly faster.

Or:

grep -xE 'bob|sam|ed' file

--
To make it insensitive to extra white space:

awk '$1~/^(bob|sam|ed)$/' file
grep -E '^[[:space:]]*(bob|sam|ed)[[:space:]]*$' file

Thanks for all your comments. The use of '^' and '$' work only if the keyword is the only word in the sentence. What if the keywords appear in the middle of a sentence? For example,

 
monday bob plays football
tuesday bobby plays hockey
wednesday sam plays volleyball
thursday sammy plays basketball
friday ed plays baseball
saturday eddie plays soccer

What grep command only gives me 'bob, sam, ed'?

The following will give you lines containing bob, sam, or ed on a line by themselves, at the start of a line followed by a space, at the end of a line preceded by a space, or in the middle of a line with a space before and after the word:

grep -E '(^(bob|sam|ed)$)|(^(bob|sam|ed) )|( (bob|sam|ed) )|( (bob|sam|ed)$)' file
1 Like
grep -E '(^|[^[:alpha:]])(bob|sam|ed)([^[:alpha:]]|$)' file

You mean lines that contain bob sam or ed, right?

Don, thanks for your assistance...simple and elegant. It works great!