How to use grep in Linux

Andrei Maksimov

Andrei Maksimov

0
(0)

One of the most commonly used operations in Linux terminal are searching through text files and filtering standard output or error streams. Linux provides a great tool which allows us to solve that task with ease – grep. In this article we’ll cover the most common use-cases for grep which will definitely simplify your daily routine.

What is grep

Grep stands for Global Regular Expression Print. This is a very handy utility when it comes to searching through a large set of text files (logs, for example).

Grep is the most useful command on Linux/Unix for system administrators, developers and DevOps engineers. The main purpose of this tool is to check for string or patterns in a specified file, or filtering other commands output.

This pattern we mentioned above, is known as a regular expression.

grep command prints out a line to the terminal with the string if it finds a match with the search query.

There are many different examples of using grep, so, let’s take a look how and when you can use it.

Installing grep on Linux

Usually, grep is installed in most Linux systems and even small Docker containers. But if you do not have it installed on your system, you can do it by using the following command, for example:

apt-get updateapt-get install -y grep

grep usage examples

In this part of the article, we’ll cover the most common examples of using grep. 

Filtering a command output

You can use the grep command for searching and printing any line from any Linux command output that matches with the specified pattern.

In this example, we’ll check which Python 3 packages do we have in our Ubuntu system:

dpkg -l | grep python3
1. How to use grep in Linux - Filter installed packages

In this example:

  • dpkg -l will print all installed packages
  • grep will filter dpkg output and print only strings, which contain python3 string

In the same way, you can display the CPU model information, for example:

grep -i 'Model' /proc/cpuinfo
16. How to use grep in Linux - Display CPU model info

Searching string within a file

In this example, grep command will look for the string “root” in the file ‘/etc/passwd’ and print it out if the string has been found.

Usually, we’re using this command to check if the system has a user account with specified name (root in out example): 

grep root /etc/passwd
2. How to use grep in Linux - Find user account in the system

Search through multiple files

To find out the string in multiple files at once, use the grep command and specify the file names in a single row. You may use regular expressions to search through files by mask.

Let’s download publicly accessible Apache access.log:

 mkdir -p /var/log/httpd
 cd /var/log/httpd
 wget http://www.almhuette-raith.at/apache-log/access.log 
3. How to use grep in Linux - Download access

Now, let’s split this file to multiple files by 10000 lines in file:

4. How to use grep in Linux - Split file by the number of rows

Now, we can search through the files for 500 HTTP server error:

grep ' 500 ' xac xad
5. How to use grep in Linux - Search for HTTP 500 error in access

To search in all files within the current working directory, use * after the pattern.

In the example below, grep command will search for 500 server errors in all files:

grep ' 500 ' *

With the -w option in grep command, you can search for the files containing a word pattern:

grep -w 'Windows XP' *
6. How to use grep in Linux - Search for operating system in access.log file

grep command is smart enough to allow us to make search regardless of the case sensitivity of the search pattern.

To do that, we need to use -i as an argument.

Here’s the same example, but now we’re doing case insensitive filtering:

grep -i -w 'windows xp' *
7. How to use grep in Linux - Search for operating system in access.log file (case insensitive)

Output files containing search pattern

You can use -l option to display all the file names containing searched pattern:

grep -l -i -w 'windows xp' *
8. How to use grep in Linux - Output files containing search pattern

Count matches per file

If you want to know the number of times your pattern matched in all files, add the -c option:

grep -c -i -w 'windows xp' *
9. How to use grep in Linux - Count search pattern matches per file

Number of lines before searched pattern

To view the lines in a file before the search pattern, add -B argument followed by the count of numbers you want to retrieve from the file:

grep -B 3 -i -w 'windows xp' xaf
10. How to use grep in Linux - Print N lines before search pattern match

Number of lines after searched pattern

Similarly, you can use -A argument to specify the count of lines to print after the searched pattern:

grep -A 3 -i -w 'windows xp' xaf
11. How to use grep in Linux - Print N lines after search pattern match

Print line number for search pattern match

To view the line number of the searched pattern found, you can use -n argument:

grep -n -i -w 'windows xp' xaf
12. How to use grep in Linux - Print line number for search pattern match

Matching the beginning of the string

In the following example, we’ll use grep command to find all requests originated from the specific IP address.

All the searched lines should start from the 5.34.180.192 term.

grep "^5.34.180.192" xaf
13. How to use grep in Linux - Matching the beginning of the string

Matching the end of the string

Add $ to the end of the pattern to find lines ending with the searched string:

grep "Chrome/62\" \"-\"$" xaf
14. How to use grep in Linux - Matching end of the string

As soon as our search string contains " symbols, we are escaping them with the \.

We can use grep to search multiple patterns at once. Add -e argument before every search pattern:

grep -e "Chrome/62\" \"-\"$" -e "15/Mar/2021:08:35:23" xaf
15. How to use grep in Linux - Matching multiple patterns at a time (AND condition)

Here, we’re searching all strings in the file which are ending on Chrome/62" "-" AND contain specific date and time 15/Mar/2021:08:35:23.

Changing output color

As colored output increases the readability, you can change it to your favorite color by setting GREP_COLOR environment variable:

GREP_COLOR='1;35' grep --color=always 'admin' /etc/passwd
17. How to use grep in Linux - Change output color

You can get more information about the GREP_COLOR variable at the official grep documentation.

Summary

The grep command is extremely useful when it comes to filtering content of the text files or commands output result. In this article, we’ve covered the most commonly used grep commands, which will streamline your shell experience.

We hope this article was useful for you. If so, please, help us to spread it to the world.

How useful was this post?

Click on a star to rate it!

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Top rated Udemy Courses to improve you career

Subscribe to our updates

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Want to be an author of another post?

We’re looking for skilled technical authors for our blog!

Leave a comment

If you’d like to ask a question about the code or piece of configuration, feel free to use https://codeshare.io/ or a similar tool as Facebook comments are breaking code formatting.