Using grep command in Linux


Grep is an acronym of Global Regular Expression Print. The grep is a command-line utility that is used to search for a specific pattern or sequence of characters in a text file. This pattern or sequence of characters is known as a regular expression.

It prints all the lines matching with the given pattern on your screen. The grep command is usually piped with some other command in the terminal. It is a very useful tool while searching for something in larger files such as log files.

In this article, we will explain see the usage of the grep command in Linux with some examples.

How to use grep command on Linux

The syntax of using grep command on a Linux system is given below-

grep [options] pattern [files]

You can find a detailed list of options on the grep command’s manual page.

Searching in a file

We have a sample text file called testfile.txt which contains some text. You can see the content of this file using the cat command in Linux –

cat testfile.txt

This will display the text of the file testfile.txt as given in the image below –

Search for a pattern in a file

Use the following command to search for the string “Linux” in the text of the testfile.txt file.

grep "Linux" testfile.txt

As you can see in the image below pattern is highlighted in the text –

Find the number of lines containing a given pattern

You can use the option -c while searching for a pattern in a file to display the number of lines that contain a given pattern.

grep -c "Linux" testfile.txt

See the given image –

That means there are three lines that contain the string “Linux”.

Display the matched string by using option -o

You can display only the matched pattern using the option -o with the grep command.

grep -o "Linux" testfile.txt

you can see the output in the given command –

Ignore case in grep searches

The grep searches are case sensitive so by using the option -i, You can make grep to search for pattern ignoring case.

grep -i "linux" testfile

This will display all the strings matches with the pattern “linux” either in capitals or small or a mix of both.

Using grep with other commands

You can pipeline the output of a command as the input to grep to customize the search. For example to find the directories or files in your current working directory that were modified in the month of January, use the command as given below –

ls -l | grep -i "Jan"

You can view the output in the image –

There are so many ways in which you can use the grep command in Linux. You can view the manual page of grep for more option that can be used with this command –

man grep

Conclusion

Ok now if you have a query related to using grep and related command in Linux then write us in the command below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.