Using grep/egrep to find out which file contains a word or string in Unix or Linux

If you need to find out which file in a directory contains a specific word then the grep command is your friend.

Here is an example, if you wanted to find out which file in the directory /home contains the word groundhog.

grep –i “groundhog” /home/*
/home/shadow:Today is groundhog day

The –i option means grep will ignore upper/lower case distinction during comparisons.
The word to search for is enclosed in double quotes, “groundhog”.
/home is the directory to search in and the * signifies all files.
The file /home/shadow contains the word groundhog, the content of the line containing the word groundhog is displayed on screen.

But what if you wanted to search for a string of words. Grep only searches for a single word. Egrep will search all files for a string of words. Here is an excerpt from the man pages of Solaris 10.

The egrep (expression grep) utility searches files for a
pattern of characters and prints all lines that contain that
pattern. egrep uses full regular expressions (expressions
that has string values that use the full set of
alphanumeric and special characters) to match the patterns.
It uses a fast deterministic algorithm that sometimes needs
exponential space.

Below is an example of egrep.

egrep –i “Apple announces the release of the ipad” /home/*
/home/obama: Today Apple announces the release of the ipad

Be Sociable, Share!

4 comments for “Using grep/egrep to find out which file contains a word or string in Unix or Linux

  1. Clif Smith
    July 23, 2010 at 1:59 pm

    If you want to look throughout directory trees:

    find . -exec grep -q whatever ‘{}’ \;

  2. Clif Smith
    July 23, 2010 at 1:59 pm

    If you want to look throughout directory tree(s):

  3. SEO
    February 23, 2010 at 10:25 pm

    A good lesson for me today, thank you.

  4. google search trends
    February 7, 2010 at 6:34 am

    Keep working ,great job!

Leave a Reply

Your email address will not be published. Required fields are marked *