grep: Searching for Words

 in
A command to help you find a specific word or a sentence in a file.

Within Linux (or any other UNIX), many people make use of filters, small programs (black boxes) that read input from standard input (stdin), do something with this input, and return the result to standard output (stdout).

Linux has many filters. Some examples are:

  • wc: print the number of bytes, words and lines in a file

  • tr: translate or delete characters

  • grep: print lines matching a pattern

  • sort: sort lines in a file

  • cut: cut selected fields from a file

The easiest way to learn these filters is to use them. This may seem daunting at first, since you may not know all the capabilities of these filters. I will describe the functions of grep so that you can benefit from its power.

I will be using this article (article.txt) as the input file for all the examples.

The Syntax

The syntax of the grep command is as follows:

grep [ -[[AB] ]num ] [ -[CEFGVBchilnsvwx] ]\
[ -e ] pattern| -file ] [ files... ]

I use GNU grep Version 2; if you're using another version, you may have slightly different options. I will touch on only those options I use most. To learn more about the grep command, see the man page. Variants of the grep command are egrep and fgrep. grep includes flags to simulate these commands: -E for egrep and -F for fgrep.

The simplest form of the command is:

grep flip article.txt

This will search for the word “flip” in the file article.txt and will display all lines containing the word “flip”.

grep also accepts regular expressions, so to search for “flip” in all files in the directory, the following command can be given:

grep flip *

All lines in all files which contain the word “flip” will be displayed, preceded by the file name. Thus, the first line of the output will look like this:

article.txt:grep flip article.txt
The line begins with the name of the file containing the word “flip”, followed by a colon, then the appropriate line.

Sometimes you may want to define the search for special characters or a word combination. To do this, put the expression between quotes so that the whole expression/pattern will be treated as one. The command would then look like this:

grep -e "is the"

I put the -e (i.e., do pattern search) option in this example just for demonstration purposes. It is not necessary to specify, as it is the default value.

To see the line numbers in which the pattern is found, use the -n option. The output will look like that shown above, with the file name replaced by the line number before the colon.

Another option which provides us with a number is the -c option. This option outputs the number of times a word exists in a file. This article contains the word “flip” 10 times.

> grep -c flip article.txt
10
grep and speed

You may now be able to think of many ways in which you might use grep. For any command you use often, speed is important. Normally, grep can do its job quickly. However, if the search is being done over many large files, the results will be slower to return. In this case, you can speed up the process by using either fgrep or egrep. fgrep is used only for finding strings, and egrep is used for complicated regular expressions.

Conclusion

File names, words, sentences and numbers can all be found quickly using grep. In addition, using the grep command together with other filters can be very powerful and prove to be of great value. For example, you could search a statistics file and sort the output by piping it through the sort and cut commands (see man pages):

grep ... | sort ... | grep ... | cut ... > result

This has been a quick introduction to get you started and rouse your curiosity to learn more about grep and other filters.

Jan Rooijackers works for Ericsson Data Netherlands (DSN) as an IT engineer. One of his favorite hobbies is programming (Tcl/Tk) and trying out new things in the computer world. He spends as much time as he can with his wife and two sons. He can be reached at dsnjaro@apskid.ericsson.se.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

grep -c 'searchstring' does

Anonymous's picture

grep -c 'searchstring' does not give you the TOTAL count of the searchstring in a file. It just gives you the TOTAL NUMBER OF LINES "containing" the search string.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState