Home Tutorials Training Consulting Products Books Company Donate Contact us









NOW Hiring

Quick links

Share

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

Flag

Example

Description

-r

grep -r text filepattern

Searches also in subdirectories of the specified filepattern.

-n

grep -n text filepattern

Prints the line number of output.

-H

grep -H text filepattern

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

-c

grep -c text filepattern

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

-l

grep -l text filepattern

Lists the files which includes the search term.

-L

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. About this website

5. Links and Literature

5.1. vogella GmbH training and consulting support

TRAINING SERVICE & SUPPORT

The vogella company provides comprehensive training and education services from experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both public and inhouse training. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended”.

The vogella company offers expert consulting services, development support and coaching. Our customers range from Fortune 100 corporations to individual developers.

Copyright © 2012-2017 vogella GmbH. Free use of the software examples is granted under the terms of the EPL License. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.

See Licence.