Home Tutorials Training Consulting Books Company Contact us

Get more...

Training Events

The grep command. This tutorial explains the usage of the grep command for searching for regular expressions in files.

1. Grep

Grep is a command line tool to search for regular expressions. Grep will print the matching line to the output and with the --color flag you can highlight the matching strings.

The usage of the Grep command is demonstrated by the following example.

# search for Strings
grep searchterm filename
grep searchterm /etc/*

# if you want to use regular expression uses quotes
grep "e*tools" /home/vogella/

Use the -r "recursive" option to search a directory and all files included within it.

# search the "hello" string in all files and
# subdirectories of the current directory
grep -r "hello" .

# same as above but only list the file names
grep -rl "hello" .

# you can exclude directories from the search
# the following excludes all directories called ".git" from the seach
grep -r --exclude-dir='.git' "hello" .

2. Important flags for using grep

The most important flags of the grep command are listed in the following table.

Table 1. Flags for the grep command





grep -r text filepattern

Searches also in subdirectories of the specified filepattern.


grep -n text filepattern

Prints the line number of output.


grep -H text filepattern

Includes the filename always in the output. By default the filename is only included if several files are searched.


grep -c text filepattern

Counts the occurrences of the search term in the specified files.


grep -l text filepattern

Lists the files which includes the search term.


grep -L text filepattern

Lists the files which do not include the search term.

3. Chaining the grep

Grep is frequently used together with the find command. For example the following will case-insensitive search for the pattern ".Legacy..xml" through the content of all files which ends with'`".java"` and lists them.

find . -name "*.java" -print0 | xargs -0 grep -i ".*Legacy.*xml"

4. Links and Literature

Legal Privacy Policy Change consent