grep Command in Linux With Examples

February 29, 2024

The grep command is primarily used to streamline and automate text processing and data extraction tasks.

System administrators and developers use grep to search log files for specific entries, locate variables and functions within codebases, and detect system-related issues.

Learn about grep syntax and usage scenarios through a set of practical examples.

grep command in Linux.


  • Access to a command line/terminal window.
  • A user with valid permissions to access the necessary files and directories.

What Is grep?

Grep is a Linux command-line tool that allows users to search files for a specified textual pattern. When grep finds a match, it prints lines containing that pattern to the terminal.

By default, the grep command outputs entire lines that contain the match. Users can utilize grep options to include additional context around the match or show only matching parts of the line.

Note: A line in a text file is a sequence of characters followed by a line break.

grep Syntax

In its basic form, the grep command consists of three parts:

  • The grep command.
  • The pattern you are searching for.
  • The file name through which grep searches.

The syntax is as follows:

grep '[search_pattern]' [file_name]

Single quotation marks (') are not mandatory for simple patterns without special characters or spaces, but it is good practice to use them.

For example, to search for the term cloud computing in the example_file2.txt file, enter:

grep 'cloud computing' example_file2.txt
Syntax of the grep command.

If the target file is not within the working directory, specify the file's full path:

grep 'cloud computing' /home/phoenixnap/Documents/example_file2.txt

grep commands support multiple options, pattern variations, and file names. Users can combine as many options as necessary to get the needed results.

Note: Make sure to use the correct case when running grep commands, as it is case-sensitive by default.

grep Options

The following table lists common grep options. They allow users to perform complex actions, targeted searches, and automate many grep functionalities.

-iThe search ignores differences between uppercase and lowercase letters.
-vDisplay only lines that do not match the search pattern.
-wMatch only whole words.
-r or -RSearch through subdirectories for the pattern. -R also follows symbolic links.
-xMatch only whole lines.
-lList files with the matching pattern only once.
-LList files that do not contain the pattern.
-cCount how many lines match the search pattern.
-oDisplay only the matching part of each line.
-aSearch binary file as text.
-m NUMStop searching a file after matching the following number (NUM) of lines.
-A NUMShow the following number (NUM) of lines after each matching line.
-B NUMShow the following number (NUM) of lines that precede each matching line.
-C NUMShow the following number (NUM) of lines around matching lines, combining the effects of
-A and -B.
-nShow the line number for each matching line.
-e or -EUse extended regular expressions for complex patterns.
-hDon't show file names when searching multiple files.
-qDo not display results; only indicate if there were any matches.
-sHide errors about files that can't be found or read.

grep Examples

The following examples show how to apply grep options and conduct searches more efficiently.

Search a File

Enter the following command to search a file for a specific character pattern:

grep 'bare metal' example_file2.txt

Replace bare metal and example_file2.txt with the search pattern and file you want to search.

Search for pattern using grep.

By default, grep prints every line from example_file2.txt that contains the pattern bare metal.

Ignore Case in Grep Searches

grep commands are case-sensitive. Use the -i option to display both uppercase and lowercase results:

grep -i 'bare metal' example_file2.txt
Search with grep regardless of case.

The output contains lines with the pattern, regardless of the case.

Inverse Search

You can use grep to print all lines that do not match a specific pattern. To invert the search, append -v to the grep command:

grep -v 'bare metal' example_file2.txt

The terminal prints all lines from the example_file2.txt that do not contain the bare metal search criterion.

Search Multiple Files

To search multiple files, insert the filenames you want to search, separated by a space. In this example, the grep command searches for the word server in example_file1.txt, example_file2.txt, and example_file3.txt:

grep 'server' example_file1.txt example_file2.txt example_file3.txt

The terminal prints the matching lines along with the file name where each match is found.

Search multiple files using grep.

Append as many filenames as necessary. The terminal prints the corresponding line prefixed with the filename for every match grep finds.

Note: Learn how to use the xargs command with grep to search for a string in a list of files.

Search All Files in Directory

To search all files in the current directory, use an asterisk (*) instead of a filename at the end of a grep command.

In this example, the search pattern is ransomware:

grep 'ransomware' *
Search all files in directory using grep.

The system prints each line that contains the term ransomware and the name of the file where the match is found.

Search for a String in Files with Specific Extensions

Use the asterisk (*) wildcard to limit searches to files with certain extensions:

grep 'ransomware' *.txt

grep searches for the ransomware pattern in all files with a .txt extension within the current directory.

Find Whole Words Only

grep allows you to search and print the results for whole words only. To search for the word server in all files in the current directory, append -w to the grep command:

grep -w server *

This option ensures that only lines containing the exact word server are printed, along with the names of the files in which they are found.

Using the -w option with grep.

In this example, the output does not include lines containing the plural form servers.

Search Subdirectories

To recursively search all files, including subdirectories, add the -r operator to the grep command:

grep -r phoenix *
Search sub-directories in Linux using grep.

The system prints matches for all files in the current directory and subdirectories, including the exact path with the filename. Use this option carefully, as searching for a common word across multiple directories can take time.

The -R option enables you to follow symbolic links within directories and extend the search to linked files and directories.

Show Lines That Exactly Match a Search String

The grep command prints entire lines when it finds a match in a file. Add the -x option to print lines that completely match the search string:

grep -x 'Spoofing' example_file1.txt

The output displays lines that exactly match the search pattern only. If there are any other words or characters in the same line, grep does not include them in the search results.

The image shows grep results without and with the -x operator:

Display lines that exactly match the search pattern in grep.

List Names of Matching Files

To retrieve the names of the files that contain a word or string of characters and exclude the actual lines, use the -l operator:

grep -l 'server' *
List names of files containing the pattern using grep.

The output shows the filenames that contain server but does not print the corresponding lines.

grep does not search subdirectories it encounters but may display warnings such as grep: temp: is a directory. Combine the recursive search operator -r with -l to include all subdirectories in your search.

Count Number of Matches

grep can count how many lines contain a pattern in one or more files. Use the -c operator to count the number of matching lines:

grep -c server *
Using grep to count number of patterns in file.

The command displays the number of lines that contain the pattern server for each file in the current directory.

Show Only the Matched Part of the Line

Use the -o option to show only part of the line that matches the search pattern rather than the entire line:

grep -o 'server' example_file2.txt
Using grep with the -o option.

This command displays only the parts of example_file2.txt that match the pattern.

Search in Binary Files

Use the grep command with the -a option to search for a string in a binary file:

grep -a 'string' binary_file1

The -a option instructs grep to treat the binary file as text.

Limit grep Output to a Fixed Number of Lines

Individual files, such as log files, can contain many matches for grep search patterns. Limit the number of lines in the grep output by adding the -m option and a number to the command:

grep -m3 'server' example_file2.txt

In this example, the terminal prints the first three matches it finds in the example_file2.txt file.

Limit the number of lines in grep output.

If you do not specify a file and search all files in a directory using the asterisk (*), the output prints the number of results specified in the command from every file. The output also shows the filename that contains the matches.

Display Number of Lines Before or After a Search String

To add more context to grep search results, use the NUM option.

The -A NUM option displays a specified number of lines after a match. For example, the following command instructs grep to print 2 additional lines after the matched pattern:

grep -A 2 'ransomware' example_file1.txt
Display lines after a grep match.

The -B NUM option displays lines before a match. The following command shows 2 additional lines before each ransomware pattern match.

grep -B 2 'ransomware' example_file1.txt
Display lines before grep search pattern.

The -C NUM option displays the specified number of lines before and after the match. The following command shows 2 lines before and after the ransomware match:

grep -C 2 'ransomware' example_file1.txt
Show lines before and after grep search result.

Display Line Numbers with grep Matches

It is useful to see the line numbers when grep finds multiple matches. Append the -n option to any grep command to show the line numbers.

Use the following command to show two lines before and after each match, along with their line numbers:

grep -n -C 2 ransomware example_file1.txt
Add line number to grep output.

The command example combines -n for line numbers with -C 2 to display two lines before and after each match for the ransomware pattern in example_file1.txt.

Search for Multiple Patterns

Use the -e option to search for multiple patterns in a single grep command:

grep -e 'server' -e 'cloud computing' -e 'phoenix' example_file2.txt
Search for multiple patterns in single grep command.

Alternatively, use grep -E (equivalent to the older egrep command) for a similar effect with extended regular expressions:

grep -E 'server|cloud computing|phoenix' example_file2.txt

In this example, grep searches for lines that match server, cloud computing, and phoenix in example_file2.txt.

Use of Regular Expressions in Searches

Users can append regular expressions to the grep command to perform complex pattern matching. The following command searches example_file1.txt for lines that start with any letter:

grep '^[a-zA-Z]' example_file1.txt

Regular expressions like these are useful for filtering out empty lines or lines beginning with special characters or numbers.

Use grep with Pipes

grep can be combined with other commands through piping (|) for more complex searches or data processing.

In this example, the cat command is used to display the content of example_file2.txt and pipes it into grep to filter lines that contain the search pattern:

cat example_file2.txt | grep 'server'
Using pipe to combine cat and grep command.

Piping enables you to perform advanced grep search operations and interact with other command-line utilities.


After going through all the commands and examples, you know how to use grep to search text files from the Linux terminal.

The grep command has many more useful options and can be combined with the find command to search thousands of files at a time.

Was this article helpful?
Goran Jevtic
Goran combines his leadership skills and passion for research, writing, and technology as a Technical Writing Team Lead at phoenixNAP. Working with multiple departments and on various projects, he has developed an extraordinary understanding of cloud and virtualization technology trends and best practices.
Next you should read
Linux Commands Cheat Sheet
November 2, 2023

A list of all the important Linux commands in one place. Find the command you need, whenever you need it or download our Linux Commands Cheat Sheet and save it for future reference.
Read more
How to Run Linux Commands in Background
July 5, 2023

Executing Linux commands in the background allows users to avoid waiting for one process to complete before entering another command. This guide explains different ways to run Linux commands in the background.
Read more
How to Use Sed to Find and Replace a String in a File
September 22, 2022

The sed command is one of the oldest and most useful command-line tools for text transformation. Learn how to utilize the most commonly used feature of sed: finding and replacing a string in a file.
Read more
gawk Linux Command With Examples
September 15, 2022

The gawk command is a powerful text-processing and data-manipulating tool. Read this guide to learn how to use gawk.
Read more