Whenever you use a simple grep command to find a single word or phrase in a file, you run the risk of getting a lot of extra "stuff" you didn't want to see. Grep for "not" and you get "nothing", "notes", "notary" and "notwithstanding". Grep for "hub" and you get "chubby", "hubby", "hubris" and "rhubarb". You can try looking for the word of your choice by putting blanks in front of and behind the word, but you then run the risk of missing your target text if it sits at the beginning or the end of a line. Here are two grep commands that will do just what you want.
The easiest of the two commands is to use grep's -w option. This will find only lines that contain your target word as a complete word. Run the command "grep -w hub" against your target file and you will only see lines that contain the word "hub" as a complete word.
$ grep -w hub /usr/dict/words hub
That's much different than this:
$ grep hub /usr/dict/words chub chubby hub hubbub hubby hubris rhubarb Schubert Thuban
You can also use the regular expression \< and \> delimiters that select whole words. Don't forget to put your expression in quotes as shown.
$ grep "\<hub\>" /usr/dict/words hub
Either of these tricks will keep you from getting "catharsis" and "catatonic" when you only want lines containing "cat". This sure beats looking for a whole word by grepping for " cat ", "^cat " and " cat$". Besides, these options wouldn't have a chance of finding your target text if it appeared inside quotes or following by some character other than a blank while still clearly a whole word:
$ grep -w cat program.c printf("Hello, cat\n");
The -w and \< \> options for selecting whole words also work for phrases. If you want to find instances of "I want cats" in a large file of personal aspirations while avoiding "I want catsup", either of these commands would work just fine:
$ cat wish-list I want my treehouse to be completed I want a nap I want piles of money I want a vacation I want some new friends I want cats I want catsup I want it all $ grep cats wish-list I want cats I want catsup $ grep -w "I want cats" wish-list I want cats $ grep "\<I want cats\>" wish-list I want cats
The grep command's -w option is explained in the man page as searching for "the expression as a word as if surrounded by \< and \>" and it does just that.
If you want your finds to include the line number, just add -n as in:
$ grep -nw cats wish-list 6:I want cats $ grep -nw cats * wish-list:6:I want cats
If you don't want to see file names when you grep on multiple files, use -h:
grep -wh cats * I want cats
The grep command is a lot more versatile than I remembered. It pays to read man pages now and then. These are very useful options!
This article is published as part of the IDG Contributor Network. Want to Join?