How do I find text in a file?
Author: Deron Eriksson
Description: This Linux tutorial demonstrates how to find text in a file using the grep command.
Tutorial created using: CentOS release 4.6


The "grep" command can be used to locate text in a file or files. The grep command has many, many options. Documentation about this command and its options can be obtained from "grep --help" and "man grep".

The text to find is represented by a regular expression. Regular expressions allow for very powerful text searching to be performed. Commonly used features of regular expressions include wildcards (the "." character can represent any single character) and ranges ("[b-dh]at" matches bat, cat, dat, and hat).

Here are a few examples. The first grep command searches for the text "mojo" in the commons-lang-2.4.pom file, and outputs the lines that contain "mojo".

grep mojo commons-lang-2.4.pom

Now, let's replace "mojo" with "m.jo". This matches all the previous "mojos". If the file contained text such as "majo", this would also be returned as a match.

grep m.jo commons-lang-2.4.pom

The following search text features a range, [jk]. This matches "mojo" and "moko".

grep mo[jk]o commons-lang-2.4.pom

By default, no line numbers are returned. If you'd like to see the line numbers in addition to the lines featuring the matches, you can do so with the "-n" switch.

grep -n mojo commons-lang-2.4.pom
grep commands

The grep command is very powerful, and so are regular expressions. One thing to be aware of is that there are different standards for regular expressions. You may want to check your grep version (via "grep --version") to see which version of grep you have. Your Linux probably is using GNU grep. If you are using a different grep, the regular expressions that you use may be slightly different.