Categories
Linux

How to Use Grep Command in Linux

Understanding grep command with practical examples to easily filter and display the file content

GREP stands for ‘Global Regular Expression Print’. It is a useful command-line utility provided by Linux, to search for the text line which matches the pattern provided by the user.

Advertisements

grep takes the input from the user in the form of strings or words which the user wishes to search in a particular file. The command then checks the file specified by the user for this pattern and then returns the lines that match the pattern provided.

It does an excellent job by filtering the content of a file thus making our task easier to search particular content on single or multiple files simultaneously.

In this article, let us review the functioning of the grep command with some practical examples in detail.

Options available with grep command

Advertisements

These are some of the fundamental options you will be using frequently with the grep command.

OptionDescription
-iFor a case-insensitive search
-rTo recursively search for all the files in the specified directory and its subdirectories
-cTo display the total number of times a string appears
-vTo display the non-matching lines
-w Filter for that particular word used separately

Using the grep command

grep command is usually used with the pipe (|) utility. It can be implemented with the shell pipe when you want to use it with some other Linux commands. Although, grep can also be used individually without the pipe (|) utility.

Let us see at some of the basic syntaxes of the grep command with and without the pipe utility.

Let me first show you the sample text file I’ll be using to illustrate the grep command.

INDIA IS A BEAUTIFUL COUNTRY OF PEACE LOVING PEOPLE. india stands on three pillars of legislature, executive and judiciary. India Is a Beautiful Country Of Peace Loving People. India cares for the people as it's resource cartesian coordinates importance of all th cartesian coordinates. Following are two empty lines. use of a bullock cart is a common sight in the village for the agrarian chores. This is the end of the sample file.

grep used with pipe ( | ) utility

Advertisements

grep command can be implemented along with other Linux commands using the shell pipes. Like, using the cat command to display the content of the file but at the same time piping the output using the grep command to display only the content which you desire to see. This will be more clear when we go through the example.

Syntax:

[command] | grep [string]

Example:

cat sample.txt | grep legislature

Here, I have used the cat command to display some lines from the ‘sample.txt’ file. Only those lines are to be displayed which contains the word ‘legislature’ in it and ignore the rest of the lines.

Output:

gaurav@ubuntu:~/workspace$ cat sample.txt | grep legislature india stands on three pillars of legislature, executive and judiciary. gaurav@ubuntu:~/workspace$
Advertisements

grep used without pipe ( | ) utility

grep can be even used directly as an individual command without using the pipe ( | ) utility.

Syntax:

grep [string_to_be_searched] [filename]

Example:

grep India sample.txt

Output:

India Is a Beautiful Country Of Peace Loving People. India cares for the people as it's resource
Advertisements

Thus, I have used the grep command directly to filter the lines which contain the string ‘India’ from the text file ‘sample.txt’.


Case-insensitive search using grep command

Linux is very cautious about the case-sensitivity when we fire the commands on the terminal. This requires the user to be careful about the case of the string put into the command.

Let us see this through an example.

grep peace sample.txt

In this case, we won’t get an output as there exists no word as ‘peace’ in the sample file. We have the word ‘Peace’ with a capital ‘P’. The word is the same but when we use the grep command without any option, it searches for the exact match in the file, disregarding any changes in the letter case.

To avoid this ambiguity, you can simply use the -i option which literally tells the grep command “forget about the case I have put the string in, and just search for all the matching patterns in the file.”

Advertisements

Syntax:

grep -i [string] [filename]

Example:

grep -i peace sample.txt

Output:

INDIA IS A BEAUTIFUL COUNTRY OF PEACE LOVING PEOPLE. India Is a Beautiful Country Of Peace Loving People.

All the matching lines are displayed irrespective of the case in which the matching string is.


Recursive search using grep command

The -r option will search for all the files in a directory and all its sub-directories which matches the string pattern provided by the user in the command.

Advertisements

Syntax:

grep -i -r [string] [file_path]

Example:

grep -i -r tomcat /home/gaurav/workspace

The string here is ‘tomcat’ and it will be searched in the directory workspace. All the subdirectories and files in the ‘workspace’ directory will also be scanned to match the string pattern provided.

Output:

./context_log.policy:// catalina.policy - Security Policy Permissions for Tomcat 7 ./context_log.policy:// Note: If tomcat-juli.jar is in ${catalina.base} and not in ${catalina.home}, ./context_log.policy:// grant codeBase "file:${catalina.base}/bin/tomcat-juli.jar" {..} ./context_log.policy:grant codeBase "file:${catalina.home}/bin/tomcat-juli.jar" { ./context_log.policy: permission java.lang.RuntimePermission "accessClassInPackage.org.apache.tomcat.websocket.server"; ./context.xml: <!-- Uncomment this to disable session persistence across Tomcat restarts --> ./catalina.properties:# - Tomcat Bootstrap JARs ./catalina.properties:# - Tomcat API JARs ./catalina.properties:# - Tomcat JARs ./catalina.properties:# - Common non-Tomcat JARs ./catalina.properties:org.apache.catalina.startup.TldConfig.jarsToSkip=tomcat7-websocket.jar ./catalina.properties:tomcat.util.buf.StringCache.byte.enabled=true ./catalina.properties:#tomcat.util.buf.StringCache.char.enabled=true ./catalina.properties:#tomcat.util.buf.StringCache.trainThreshold=500000 ./catalina.properties:#tomcat.util.buf.StringCache.cacheSize=5000 ./server.xml: pathname="conf/tomcat-users.xml" /> ./server.xml: <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" ./server.xml: <Connector executor="tomcatThreadPool" ./server.xml: every request. The Engine implementation for Tomcat stand alone ./tomcat-users.xml:<tomcat-users> ./tomcat-users.xml: <user username="role1" password="tomcat" roles="role1"/> ./tomcat-users.xml:</tomcat-users> ./web.xml: <!-- loaded into this instance of Tomcat. As each application is --> ./web.xml: <!-- used by Tomcat to support JSP pages. Traditionally, this servlet -->

NOTE: While using the -r option with the grep command we need to provide the path of the file and not the filename


Searching whole words only with grep command

Advertisements

Many times the case is that you will be searching for one word but you will end up populating your terminal with the matching lines which does contain your matching word but not as an individual word. You may see the lines which contains some words whose subpart is the string that you have entered.

Confused with this? Don’t worry, it is much easier to understand once you get the example.

Example:

Here, I want to search an individual word ‘cart’ and display all the lines matching to this word in the file ‘sample.txt’.

grep -i cart sample.txt

Output:

Cartesian coordinates importance of all the Cartesian coordinates. use of a bullock cart is a common sight in the village for the agrarian chores The cart went missing as the boy left it loose.
Advertisements

In the output, you can observe that the word ‘Cartesian’ also contains the word ‘cart’ and hence, the lines containing the word ‘Cartesian’ are also displayed even though we do not want them to be displayed.

You can use the -w option with the grep command to solve this ambiguity.

Syntax:

grep -i -w [string] [filename]

Example:

grep -i -w cart sample.txt

Output:

use of a bullock cart is a common sight in the village for the agrarian chores. The cart went missing as the boy left it loose.
Advertisements

Now, when you have used the –w option with grep you will get only the lines in which the word ‘cart’ is used as a whole.


Inverted search using grep command

grep command can also be used in a reverse fashion. We can use the grep command oppositely by hiding the matching lines and only displaying the lines where the match is not found. You can do this using the -v option with the grep command.

Syntax:

grep -i -v [string] [filename]

Example:

grep -i -v resource sample.txt

Output:

INDIA IS A BEAUTIFUL COUNTRY OF PEACE LOVING PEOPLE. india stands on three pillars of legislature, executive and judiciary. India Is a Beautiful Country Of Peace Loving People. cartesian coordinates importance of all th cartesian coordinates. use of a bullock cart is a common sight in the village for the agrarian chores. This is the end of the sample file.
Advertisements

In the output, all other lines are displayed other than the line which contains the word ‘resource’.


Counting occurrences of matching string

The output of the grep command is usually very long if the data in the file is extensive. The more the matches, the longer are the outputs of the grep command. Linux provides you with an option where you can display the number of occurrences of the match.

Syntax:

grep -i -c [string] [filename]

Example:

grep -i -c india sample.txt

Output:

gaurav@ubuntu:~/workspace$ grep -i -c india sample.txt 4 gaurav@ubuntu:~/workspace$
Advertisements

Here, the output is a number which is the number of occurrences of the word ‘India’ in the file sample.txt.

NOTE: I have used the -i option in every example to just be safe with the case sensitivity issue. In case you are sure about the case of the word you are searching for, then you can safely omit the -i option.


Conclusion

We have learnt the fundamental uses of the grep command on the Linux systems in this tutorial. We also learnt to display various content which best suits our requirements and not crowding the terminal with loads of lines. grep command will surely be a time-saver if used for scanning large data-sets.