grep Command in Linux Explained with Practical Examples

grep Command in Linux Explained with Practical Examples

The grep command is one of the most widely used tools in Linux for searching text within files and command output. It scans each line of a file and prints the lines that match a specified pattern.

The name grep stands for Global Regular Expression Print, which reflects its ability to search using simple text patterns as well as regular expressions.

The grep command supports many options that allow you to control how searches are performed and how results are displayed. In this guide, you will learn how to use the most commonly used grep options with practical examples.

grep Command Syntax

The basic syntax of the grep command is:

bash
grep [options] pattern file

Where:

  • pattern → text or regular expression to search
  • file → file or files where the search is performed
  • options → modify how the search is performed

grep Command - Quick Cheat Sheet

This quick reference summarizes the most commonly used grep command examples in Linux for searching text patterns in files and directories.

Taskgrep Command
Search for pattern in a filegrep "pattern" file.txt
Ignore case when matching patternsgrep -i error logfile.txt
Match whole words onlygrep -w error logfile.txt
Match entire line exactlygrep -x "pattern" file.txt
Invert match (exclude pattern)grep -v debug logfile.txt
Show line numbers with matchesgrep -n error logfile.txt
Count matching linesgrep -c error logfile.txt
Print only matching textgrep -o "[0-9]*" file.txt
Search recursively in directoriesgrep -r error /var/log
Follow symbolic links when searchinggrep -R error /var/log
Print filenames containing matchesgrep -l error *.log
Print filenames without matchesgrep -L error *.log
Show lines after matchgrep -A 3 error logfile.txt
Show lines before matchgrep -B 3 error logfile.txt
Show lines before and after matchgrep -C 3 error logfile.txt
Search multiple patternsgrep -e error -e warning logfile.txt
Read patterns from filegrep -f patterns.txt logfile.txt
Use extended regular expressions`grep -E "error
Search fixed strings (faster search)grep -F "connection refused" logfile.txt
Show filename with matchesgrep -H error file.txt
Hide filename in outputgrep -h error file1 file2
Highlight matches in outputgrep --color error logfile.txt
Suppress output (use exit status only)grep -q error logfile.txt
Suppress error messagesgrep -s error missingfile.txt
Search only specific file typesgrep --include="*.log" error /var/log
Exclude files from searchgrep --exclude="*.gz" error /var/log

Basic grep Command Examples

search text in a file

The most basic usage of grep is searching for a text pattern inside a file. Grep scans the file line by line and prints any line containing the matching pattern.

Example:

bash
grep error logfile.txt

This command searches for the word error inside logfile.txt and prints every line that contains it.

You can also search phrases by enclosing them in quotes.

bash
grep "connection failed" logfile.txt

search across multiple files

Grep can search for a pattern across multiple files in a single command.

Example:

bash
grep error file1.log file2.log file3.log

The output will include the filename along with the matching line.

Example output:

bash
file1.log:error connecting to database
file2.log:error opening configuration file

perform case insensitive searches

By default, grep searches are case sensitive. To ignore case differences, use the -i option.

Example:

bash
grep -i error logfile.txt

This will match all variations such as:

  • error
  • Error
  • ERROR

This option is especially useful when searching logs or user input data.

match whole words only

Sometimes a pattern may appear as part of a larger word. The -w option ensures only whole word matches are returned.

Example:

bash
grep -w log system.txt

This will match log but not words like login or logout.

count matching lines

If you only want to know how many lines contain the pattern, use the -c option.

Example:

bash
grep -c error logfile.txt

Example output:

bash
15

This means 15 lines contain the word error in the file.


Controlling grep Output

The -n option displays the line number where the match occurs.

Example:

bash
grep -n error logfile.txt

Example output:

bash
12:error connecting to database
45:error loading configuration

This helps locate the exact position of matches inside a file.

Normally grep prints the entire line containing the match. The -o option prints only the matched portion.

Example:

bash
grep -o "[0-9]*" numbers.txt

This extracts only numeric values from the file.

Example output:

bash
120
55
999

invert matches

The -v option prints lines that do not contain the specified pattern.

Example:

bash
grep -v debug application.log

This filters out all lines containing the word debug.

limit the number of matches

The -m option stops grep after a specific number of matches.

Example:

bash
grep -m 3 error logfile.txt

This prints only the first three matching lines and then stops searching the file.


Searching Files and Directories

search all files in a directory

To search a pattern in every file in the current directory, you can use the wildcard *.

Example:

bash
grep error *

This command searches for the word error in all files within the current directory.

If multiple files contain matches, grep prints the filename along with the matching line.

search recursively in directories

To search inside a directory and all its subdirectories, use the -r option.

Example:

bash
grep -r error /var/log

This command searches for the word error in every file under /var/log including all subdirectories.

Recursive search is commonly used when analyzing application logs or system logs.

search only specific file extensions

Sometimes you only want to search specific types of files such as .log or .conf. You can limit the search using the --include option.

Example:

bash
grep -r "database" --include="*.conf" /etc

This searches only .conf files in the /etc directory.

list files containing matches

If you only want to know which files contain the pattern, use the -l option.

Example:

bash
grep -l error *.log

Example output:

bash
server.log
application.log

This command prints only the filenames that contain the word error.


Working with Multiple Files

show filenames with matches

The -H option forces grep to display the filename along with each matching line.

Example:

bash
grep -H error file1.log file2.log

Example output:

bash
file1.log:error connecting to database
file2.log:error opening configuration

hide filenames in output

If you search multiple files but want to hide filenames from the output, use the -h option.

Example:

bash
grep -h error file1.log file2.log

This prints only the matching lines without displaying the file names.

list files without matches

The -L option prints filenames that do not contain the pattern.

Example:

bash
grep -L error *.log

Example output:

bash
access.log
system.log

This helps identify files where the pattern is not present.


Context Based Searches

Grep can display lines that appear before or after a match. This is useful when examining logs or understanding surrounding context.

show lines after a match

The -A option displays a specified number of lines after the matching line.

Example:

bash
grep -A 3 error logfile.txt

This prints the matching line plus the next three lines.

show lines before a match

The -B option displays lines before the matching line.

Example:

bash
grep -B 2 error logfile.txt

This prints the matching line along with the two lines before it.

show lines before and after matches

The -C option displays lines both before and after the match.

Example:

bash
grep -C 2 error logfile.txt

This shows two lines before and two lines after each match.


Searching Files and Directories

search all files in a directory

To search a pattern in every file in the current directory, you can use the wildcard *.

Example:

bash
grep error *

This command searches for the word error in all files within the current directory.

If multiple files contain matches, grep prints the filename along with the matching line.

search recursively in directories

To search inside a directory and all its subdirectories, use the -r option.

Example:

bash
grep -r error /var/log

This command searches for the word error in every file under /var/log including all subdirectories.

Recursive search is commonly used when analyzing application logs or system logs.

search only specific file extensions

Sometimes you only want to search specific types of files such as .log or .conf. You can limit the search using the --include option.

Example:

bash
grep -r "database" --include="*.conf" /etc

This searches only .conf files in the /etc directory.

list files containing matches

If you only want to know which files contain the pattern, use the -l option.

Example:

bash
grep -l error *.log

Example output:

bash
server.log
application.log

This command prints only the filenames that contain the word error.


Working with Multiple Files

show filenames with matches

The -H option forces grep to display the filename along with each matching line.

Example:

bash
grep -H error file1.log file2.log

Example output:

bash
file1.log:error connecting to database
file2.log:error opening configuration

hide filenames in output

If you search multiple files but want to hide filenames from the output, use the -h option.

Example:

bash
grep -h error file1.log file2.log

This prints only the matching lines without displaying the file names.

list files without matches

The -L option prints filenames that do not contain the pattern.

Example:

bash
grep -L error *.log

Example output:

bash
access.log
system.log

This helps identify files where the pattern is not present.


Context Based Searches

show lines after a match

The -A option displays a specified number of lines after the matching line.

Example:

bash
grep -A 3 error logfile.txt

This prints the matching line plus the next three lines.

show lines before a match

The -B option displays lines before the matching line.

Example:

bash
grep -B 2 error logfile.txt

This prints the matching line along with the two lines before it.

show lines before and after matches

The -C option displays lines both before and after the match.

Example:

bash
grep -C 2 error logfile.txt

This shows two lines before and two lines after each match.


Pattern Anchors

match lines starting with a pattern

The caret symbol ^ represents the start of a line. It can be used to find lines that begin with a specific pattern.

Example:

bash
grep "^error" logfile.txt

This command prints lines that start with the word error.

Example output:

bash
error connecting to database
error loading configuration

match lines ending with a pattern

The dollar sign $ represents the end of a line.

Example:

bash
grep "failed$" logfile.txt

This command prints lines that end with the word failed.

Example output:

bash
login attempt failed
authentication failed

Note that any character at the end, including spaces, affects the match.


Advanced grep Usage

search multiple patterns using -e

The -e option allows you to specify multiple search patterns in a single command.

Example:

bash
grep -e error -e warning -e failed logfile.txt

This command prints lines that contain any of the specified patterns.

read search patterns from a file

You can store multiple patterns in a file and let grep read them using the -f option.

Example pattern file:

bash
error
warning
critical

Run grep using the pattern file:

bash
grep -f patterns.txt logfile.txt

Grep searches for every pattern listed in patterns.txt.

exclude files or directories

When searching recursively, you may want to skip certain directories.

Example:

bash
grep -r "error" /var/log --exclude-dir=archive

This searches /var/log but ignores the archive directory.

You can also exclude files:

bash
grep -r "error" /var/log --exclude="*.gz"

search only specific file types

You can restrict searches to specific file extensions using --include.

Example:

bash
grep -r "database" --include="*.conf" /etc

This command searches only .conf files inside /etc.


Using grep with Other Commands

filter command output using pipes

The pipe operator | allows grep to filter the output of other commands.

Example:

bash
dmesg | grep usb

This displays only lines containing usb from the kernel message output.

Another example:

bash
ps aux | grep nginx

This searches for running processes containing the word nginx.

combine grep with find command

You can combine find and grep to search files matching certain conditions.

Example:

bash
find /var/log -type f -name "*.log" -exec grep "error" {} \;

This searches all .log files under /var/log for the word error.

use grep with shell variables

You can store patterns in variables and use them in grep commands.

Example:

bash
pattern="error"
grep "$pattern" logfile.txt

This searches for the value stored in the variable.


Special grep Options

search binary files as text

By default grep skips binary files. To force grep to treat them as text, use the -a option.

Example:

bash
grep -a "error" binaryfile.log

This forces grep to search the file even if it contains binary data.

run grep in quiet mode

The -q option runs grep in quiet mode, meaning it does not print output but returns a success status if a match is found.

Example:

bash
grep -q error logfile.txt

This is commonly used in shell scripts to check if a pattern exists.

suppress error messages

When searching directories recursively, grep may print permission errors. You can suppress these using -s.

Example:

bash
grep -r "error" /var/log -s

This hides error messages such as permission denied.


Frequently Asked Questions

1. What is the grep command used for?

The grep command in Linux is used to search text patterns in files or command output. It prints lines that match the specified pattern.

2. How do I search recursively using grep?

You can use the -r option to search recursively across directories. Example: grep -r error /var/log

3. How do I ignore case when using grep?

Use the -i option to perform a case insensitive search. Example: grep -i error logfile.txt

4. How do I count matches using grep?

Use the -c option to count lines that contain the pattern. Example: grep -c error logfile.txt

5. How do I search multiple files using grep?

Specify multiple files separated by spaces. Example: grep error file1.log file2.log

Summary

The grep command is one of the most powerful and commonly used tools in Linux for searching text inside files and command output. It allows users to quickly locate patterns, filter results, and extract useful information from large datasets or log files.

In this guide, we explored many practical examples of using the grep command, including:

  • searching text in single or multiple files
  • performing case-insensitive searches
  • matching whole words and counting matches
  • controlling output with line numbers and context lines
  • searching files and directories recursively
  • using pattern anchors to match the start or end of lines
  • combining grep with other commands like find and pipes
  • using advanced options such as reading patterns from files or excluding directories

Further Reading

If you want to explore more advanced pattern matching techniques using grep, you may find the following tutorials helpful:

For official documentation and detailed reference, see:

Rohan Timalsina

Rohan Timalsina

is a technical writer and Linux enthusiast who writes practical guides on Linux commands and system administration. He focuses on simplifying complex topics through clear explanations.