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

About Andrew Lin

Hi, I have always wanted to creat a blog site but never had the time. I have been working in Information Technology for over 15 years. I specialize mainly in networks and server technologies and dabble a little with the programming aspects. Andrew Lin

View all posts by Andrew Lin →