Searching files

Filters

The grep and fgrep are two of many text filters (utilities that scan a text source and retrieve records that match a given pattern). grep and fgrep report the file the sought-after pattern was found and display the lines in which it occurred. The main difference between these two commands is that grep can search for a single pattern whereas fgrep can search for multiple patterns at once.

grep

The grep command takes two parameters: the pattern to be searched for and a list of filenames to be searched. For example, to locate every line that contains the word 'volatile' in the file simulator.c, type the following command:

 $grep volatile simulator.c
  volatile int state; 

To include more than one word in the search pattern, enclose the pattern in single quotes:

 $grep 'unsigned long' simulator.c

The quotes are necessary. Otherwise, the grep command will interpret long as a filename.

When searching in multiple files, grep outputs the name of the file before the matching line. In the following command, grep searches for the token EXIT_SUCCESS in the files simulator.c and calendar.c:

 $grep EXIT_SUCCESS simulator.c calendar.c
  simulator.c: return EXIT_SUCCESS;
  calendar.c: if (stat==EXIT_SUCCESS)

Regular Expressions You may use regular expressions in a search pattern. A regular expression enables you to locate variations on a general pattern, say every word that ends in t, or patterns located at different points in the text, for example, at the end of a line. The following special characters may be used in regular expressions:

Sign Operation
^ References the beginning of a line
$ References the end of a line
. Matches any possible character
* Matches zero or more characters
[] Matches a set, or a range of characters

Suppose you're reviewing the coding practices of your team and you want to locate all occurrences of the keyword goto in every source file. The following command will do the trick:

 $grep goto *.c

Now suppose you want to locate every line that ends with { so that you can move it to the next line. Type the following command:

 $grep {$ *.c
  simulator.c: struct joystick {
  calendar.c: for (n=0; n<MAX; ++n) {
Insider: How the basic tech behind the Internet works
Join the discussion
Be the first to comment on this article. Our Commenting Policies