DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Power tools

Searching for text within files

You can use the grep command to search through files for a particular pattern.

grep ``foo'' afile

The name grep comes from the ed(C) command g/re/p, which means ``globally search for a regular expression and print it''. The grep command looks through the files you specify for lines containing the regular expression you tell it to find.

Regular expressions are a special kind of pattern that are used by many UNIX system commands. You can use regular expressions with vi, as well as with ed(C), a line editor; sed(C), a stream editor; expr(C), an expression evaluator; and awk(C), a regular-expression-based programming language.

A discussion of regular expression syntax is beyond the scope of this book; see ed(C) for all the details.

To use grep to search for words in a file, type grep, the word or words you want to search for, the files you want to look in, and press <Enter>. If you want to look for more than one word, you need to put ``double quotes'' around the words.

If you specify more than one file for grep to look in, grep tells you the name of the file in which the word was found, and it shows you the line in which the word appears. If you only specify one file to look in, grep does not tell you the name of the file. If grep cannot find the word in the specified file or files, it silently returns your prompt.

For example, to search for an entry in /etc/passwd, you could type:

   $ grep susannah /etc/passwd
   susannah:IHi3E6JQ.IJxU:12846:1014:Susannah Skyer:/u/susannah:/bin/sh
To look through all the files in the current directory for the words ``cat food,'' you could type:
   $ grep "cat food" *
   mytodo:buy cat food
In the preceding example, ``cat food'' was found in the file mytodo, in the line ``buy cat food.''

You can use grep together with other commands to search for particular lines of output. For example, to see all of the files owned by susannah in /tmp, you could type:

   $ l /tmp | grep susannah
   -rw-------   1 susannah unixdoc        0 Jun 24 16:29 Ex05064
   -rw-------   1 susannah techpubs    8192 Jun 27 16:57 Ex29109
   -rw-rw----   1 susannah techpubs    3532 Jun 24 15:48 maila14986
   -rw-------   1 susannah techpubs    2048 Jun 27 16:55 Rx29109
   -rw-rw----   1 susannah techpubs    4960 Jun 24 13:32 unixmeet
There are a variety of options with the grep command, and there are also two faster versions of grep, fgrep (fast grep) and egrep (expression grep), which you can use in some instances. See grep(C) for more information.
Next topic: Checking who is logged in
Previous topic: find / -name afile -print

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 03 June 2005