Unix Tip: Grepping on Whole Words

By Sandra Henry-Stocker  Add a new comment

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!

    Add a comment

    Post a comment using one of these accounts
    Or join now
    At least 6 characters

    Note: Comment will appear soon after you have activated your account.
    Obscene/spam comments will be removed and accounts suspended.
    The information you submit is subject to our Privacy Policy and Terms of Service.

    ITworld LIVE

    IT Management/StrategyWhite Papers & Webcasts

    White Paper

    Evaluator Group: Storage Federation - IT Without Limits (Analysis of HP Peer Motion with Storage Federation)

    As the role of IT increases within organizations, the need to move data when and where it is needed is critical to support emerging business requirements. This has become increasingly difficult due to the huge growth of data volumes. This white paper sponsored by HP + Intel evaluates a solution that aims to enable the movement of data without physical limitations. Read now and see how this could enable agility and efficiency.

    White Paper

    ESG Lab Validation Report: HP Data Protector & Deduplication Solutions

    Many organizations have deployed disk-to-disk backup technologies to improve the speed and reliability of their backup and disaster recovery operations. A growing number of these now look to data deduplication to enhance retention periods and reduce costs. This ESG Lab Validation Report sponsored by HP + Intel examines a number of backup and recovery solutions and evaluates their ease of implementation as well as their ability to improve reliability and reduce costs.

    White Paper

    Business Value of Blade

    The nature of the blade platform makes system management, monitoring and provisioning easy and efficient. Access this resource to learn how blade migration will save your data center time and money while increasing performance.

    White Paper

    Accelerate time to application value

    For your IT organization to keep pace with the business, you need a new, faster approach to infrastructure deployment-an approach that increases agility and accelerates time to application value. That's HP Converged Systems. Built on Converged Infrastructure, these systems deliver the industry's first portfolio of pre-integrated, tested, and optimized infrastructure solutions for applications running in virtual, cloud, dedicated, or hybrid environments.

    White Paper

    Converged Infrastructure for Dummies

    As you know, everything is mobile, connected, interactive, and immediate. This is exactly why organizations need a highly agile IT infrastructure in order to keep pace with extreme fluctuations in business demand. This book will help you understand why infrastructure convergence has been widely accepted as the optimal approach for simplifying and accelerating your IT to deliver services at the speed of business while also shifting significantly more IT resources from operations to innovation.

    See more White Papers | Webcasts

    Ask a question

    Ask a Question