Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Medium

Grep Command in Linux/UNIX

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Grep is a powerful command in Linux/ Unix operating systems to search for patterns or regular expressions within text files. The grep command in Linux is a powerful tool for searching text files or data streams for lines that match a specific pattern. If you're a Linux user, the grep tool can help you quickly identify and extract information from a large group of files. You can use grep to search for specified patterns, words, or phrases in one or more files at the same time.

Grep Command in Linux

In this article, we will discuss the grep Command in Linux. We will see its syntax and commonly used options for the grep command in Linux. We will also explore the various use cases of the grep command. So, whether you are a beginner or an advanced user, this article will provide you with a good understanding of how to use the grep command efficiently. So, without any delay let's get started.

What is grep Command in Linux

The term ‘grep’ stands for ‘Global Regular Expression Print.’ In Linux, the grep command is an effective text search tool. It is used to find a certain text or pattern in one or more files. The grep command searches for the pattern supplied by the Pattern parameter and outputs each line that matches to standard output. 

The patterns are limited to regular expressions in the ed or egrep style. The grep command employs a lightweight non-deterministic algorithm. It can also be used to look for text in a command's output. It is a highly useful tool for programmers and system administrators who need to search log files or other text files for specific information.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

History of grep

Implementations of grep

Installing grep Command in Linux

In this section, we will learn how to install the grep command in Linux. However, grep comes with almost every Linux distribution. If it is missing from your system, you may install it with the following command in the terminal window:

$ sudo apt-get install grep


Now, let’s look at the syntax and some of the commonly used options for the grep command with their implementation.

Syntax and Use

The syntax of the grep command is as follows:

$ grep [options] pattern [file(s)]


In the above syntax, the term pattern is the pattern that you want to search. The term file refers to that file you want to search into.

Let's look at some of the commonly used options for the grep command:

Commands Use
‘-i’, --ignore-case It searches for the line containing that particular word. It doesn't perform a case-sensitive search.
‘-v’, --invert-match It selects the non-matching lines of the given input pattern.
‘n’, --line-number It displays the line number along with the search result.
‘-r’, --recursive It performs a recursive search in all files and subdirectories.
‘-w’ It finds the exact matching word from the input file or string.
‘-c’ It counts the number of occurrences of the searched pattern.

Text File

In this article on grep Command in Linux, we will use a file named file.txt to implement the above options for grep command. It is important to get an overview of the text file that we will be using in various commands. Let’s look at the text file:

grep command Text File

Search for a String in a File

Let's learn how to search for a string in a file. For this, we will be using the grep command with the string you want to search in file_name. The search is case-sensitive.

Syntax

To search for a string in a file, run the following command with the syntax:

$ grep “string” filename

Example

Let's look at the implementation of the command, we will be searching for the string CodingNinjas from the file named file.txt.

$ grep "CodingNinjas" file.txt

Output

ninjas@ninjas-VirtualBox:-/Desktop$ grep  “CodingNinjas”   file.txt
CodingNinjas is a great platform for learning.
CodingNinjas offers courses on many programming languages.
Don't waste any more time, start learning with CodingNinjas today!
ninjas@ninjas-VirtualBox:-/Desktop$ 

Explanation

In the above output, we can see that the grep command has not only searched and exactly matched the string CodingNinjas but also printed the lines in which the string appears.

Ignoring the Case Distinctions

In the above section, we printed only the string CodingNinjas because the string was specified in uppercase. Now, we will search for string codingninjas ignoring the case distinction in a file. We will be using the grep -i command with the string you want to search in file_name.

Syntax

The syntax for grep ‘-i’ command is:

$ grep -i "string" filename

Example

Let’s look at the example of searching for a string ignoring case distinction, run the following command:

$ grep -i "codingninjas" file.txt

Output

ninjas@ninjas-VirtualBox: -/Desktop$ grep -i  “codingninjas” file.txt
CodingNinjas is a great platform for learning.
At codingninjas, you can learn a wide range of topics, from beginner to advanced.
CodingNinjas offers courses on many programming languages.
You'll find something useful at codingninjas.
Don't waste any more time, start learning with CodingNinjas today!

Explanation

In the above output, we can see that the ‘grep -i’ command has searched and matched all the lines that contain the string codingninjas. So, the lines containing whether the string CodingNinjas or codingninjas are printed. It ignores the case distinction and prints all the lines in which the string appears.

Selecting the Non-Matching Lines

We have seen ways to search and print the line that matches the desired string irrespective of the case of the letter. Now, what if we want to print that line that does not contain the desired string? For this, we will be using the grep -v commandNote that the grep -v command is case-sensitive.

Syntax

The syntax for grep ‘-v’ command is:

$ grep -v "string" filename

Example

In this example, we will not be printing those lines in which the string CodingNinjas appears. To print the line that does not contain the string, run the following command:

$ grep -v "CodingNinjas" file.txt

Output

Ninjas@ninjas-VirtualBox:-/Desktop$ grep -v “CodingNinjas” file.txt
At codingninjas, you can learn a wide range of topics, from beginners to advanced. 
If you're serious about your programming skills, you should definitely check out.
You'll find something useful at codingninjas.

Explanation

In the above output, we can see that the line that matches the string CodingNinjas is not printed else all other lines from the file are printed.

Number the Lines that contain the Searched Pattern

In pattern searching, we might want to number the lines where the string is matched. For this, we use the grep -n command. Let’s look at its syntax and implementation.

Syntax

The syntax for grep ‘-n’ command is:

$ grep -n "string" filename

Example

In this example, we will be numbering the lines in which the string CodingNinjas appears. To print the number of the line where the string is matched in the file, run the following command:

$ grep -n "CodingNinjas" file.txt

Output

ninjas@ninjas-VirtualBox:-/ Desktop$ grep -n “CodingNinjas” file.txt
1: CodingNinjas is a great platform for learning.
4: CodingNinjas offers courses on many programming languages.
6: Don't waste any more time, start learning with CodingNinjas today!

Explanation

From the above output, we can see that line 1, 4, and 6 contains the desired string CodingNinjas. As we can see, line number 2, 3, and 5 don’t contain the string CodingNinjas are skipped. We printed the number at the beginning of each line in the output console.

Searching for a String Recursively in all Directories

Now, what if the user wants to search the desired string in all directories and subdirectories? The search of the user is not only confined to a single file. If the user wants to search for the desired string in all the files the command grep -r is useful. Linux provides the grep -r command that recursively searches in all the files that match the desired string.

Syntax

The syntax for grep ‘-r’ command is:

$ grep -r "string" *

Example

In this example, we will be searching the string CodingNinjas in all files in our directories. To search the string recursively in all directories, run the following command with the syntax:

$ grep -r "CodingNinjas" *

Output

ninjas@ninjas-VirtualBox: -/Desktop$ grep -r  “CodingNinjas”  *
File2.txt: This is an example of learn linux on CodingNinjas.
File2.txt: Welcome to CodingNinjas.
file.txt: CodingNinjas is a great platform for learning.
file. txt: CodngNinjas offers courses on many platforms languages.
file.txt: Don't waste any more time, start learning with CodingNinjas today!

Explanation

In the above output, we can see that the ‘grep -r’ command has searched the string CodingNinjas in all the file, in our directory we are using only two files named file.txt and File2.txt. The string appeared in File2.txt two times whereas in the file.txt three times.

Search for Exact Matching Word

In this section, we learn the command to search for the line containing the exact word. For this, we will be using the grep -w command.

Syntax

The syntax for grep ‘-w’ command is:

$ grep -w "string" filename

Example

Now quickly look at the example to search for the exact matching string and execute the following command:

$ grep -w "great" file.txt

Output

ninjas@ninjas-VirtualBox: -/Desktop$ grep “ CodingNinjas” file.txt
CodingNinjas is a great platform for learning.
CodingNinjas offers courses on many programming languages.
Don't waste any more time, start learning with CodingNinjas today!
ninjas@ninjas-VirtualBox:-/ Desktop$

Explanation

In the above output, we can see that the string ‘great’ appears only one time. So, only one string that contains it is printed.

Count the Lines where Strings are Matched

As in the above section, Search for a string, where we searched for the string CodingNinjas, we get three lines printed. Now, counting the number of lines this way can be exhausting. For this, we can use the count of the appearance of the desired string using a single line grep -c command.

Syntax

The syntax for grep ‘-w’ command is:

$ grep -c "string" filename

Example

In this example, we will be counting the number of appearances of the string CodigNinjas. Now quickly look at the implementation to count the total number of lines where the desired pattern appears:

$ grep -c "CodingNinjas" file.txt

Output

ninjas@ninjas-VirtualBox:-/Desktop$ grep -c “CodingNinjas” file.txt
3
ninjas@ninjas-VirtualBox: -/Desktop$

Explanation

In the above output, we can see that the string ‘CodingNInjas’ appears only three times. Hence, digit 3 is printed in the output console.

Searching Patterns with Regular Expressions(REGEX)

The term REGEX stands for REGular EXpression. It is a sequence of characters used to match patterns. Let’s look at some of the examples:

Special Characters Use

^

Used to match characters at the start of a line.

Syntax: grep ^character file_name

$

Used to match characters at the end of the line.

Syntax: grep $character file_name

“.”

It matches any character.

Syntax: grep ‘.’ file_name

[ a-z ]

Used to match the characters between A and Z.

Syntax: grep ‘[a-z]’ file_name

[^ . . ]

It matches anything but what is contained inside the bracket.

Syntax: grep ‘[^..]’ file_name

Frequently Asked Questions

What is grep command Linux?

Grep is a Linux command that helps find specific words or patterns in files. It can be used with regular expressions to find and display lines that match particular criteria.

What is grep syntax?

The grep syntax is grep [options] pattern [file...] in which grep is the command, options are additional settings, the pattern is the text you want to search for, and [file...] refers to the optional files to search within.

How to do a grep search on Linux?

To perform a grep search on Linux, open the terminal and type a simple command. They are followed by the text you want to find and the file or multiple files to search within.

Conclusion

This article briefly discussed the grep Command in Linux. We have discussed the grep command in Linux and looked at its syntax and commonly used commands in the grep command. You can check out our other blogs to enhance your knowledge:

You can refer to our guided paths on the Coding Ninjas Studio platform. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc.

Topics covered
1.
Introduction
2.
What is grep Command in Linux
3.
History of grep
4.
Implementations of grep
5.
Installing grep Command in Linux
5.1.
Syntax and Use
6.
Text File
7.
Search for a String in a File
7.1.
Syntax
7.2.
Example
7.3.
Output
7.4.
Explanation
8.
Ignoring the Case Distinctions
8.1.
Syntax
8.2.
Example
8.3.
Output
8.4.
Explanation
9.
Selecting the Non-Matching Lines
9.1.
Syntax
9.2.
Example
9.3.
Output
9.4.
Explanation
10.
Number the Lines that contain the Searched Pattern
10.1.
Syntax
10.2.
Example
10.3.
Output
10.4.
Explanation
11.
Searching for a String Recursively in all Directories
11.1.
Syntax
11.2.
Example
11.3.
Output
11.4.
Explanation
12.
Search for Exact Matching Word
12.1.
Syntax
12.2.
Example
12.3.
Output
12.4.
Explanation
13.
Count the Lines where Strings are Matched
13.1.
Syntax
13.2.
Example
13.3.
Output
13.4.
Explanation
14.
Searching Patterns with Regular Expressions(REGEX)
15.
Frequently Asked Questions
15.1.
What is grep command Linux?
15.2.
What is grep syntax?
15.3.
How to do a grep search on Linux?
16.
Conclusion