Do you think IIT Guwahati certified course can help you in your career?
No
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.
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.
History of grep
Origin of the Name 'grep'
The name grep is derived from a command used in the Unix text editor ed: g/re/p, which stands for "globally search for a regular expression and print matching lines." This command allowed users to search through text efficiently by applying a pattern (regular expression) and printing the results. When a standalone command-line tool was later developed to perform similar searches outside of ed, it inherited the name grep. The simplicity and functionality of this concept made it instantly valuable to Unix users.
Development and Integration
Ken Thompson, one of the key developers of Unix at Bell Labs, created grep in 1973. At that time, Unix was still evolving as a multiuser, multitasking operating system, and there was a growing need for powerful tools to manipulate and analyze text files. Recognizing this, Thompson built grep as a fast, standalone utility that could efficiently filter input using regular expressions. Its inclusion in early Unix distributions made it a standard tool for programmers and system administrators.
Evolution and Impact
Over time, grep became an essential part of the Unix philosophy—building small, focused tools that do one job well. It evolved into several versions, including egrep and fgrep, and eventually into grep with extended options. As Unix spread into Linux and other systems, grep became a universal utility for log analysis, configuration searching, scripting, and data extraction. Its speed, simplicity, and versatility ensured its place as a core tool in the Unix/Linux toolkit, still heavily used decades after its creation.
Implementations of grep
1. grep (GNU grep)
This is the default version found in most Linux distributions. It supports basic regular expressions and various options like -i for case-insensitive search or -n to show line numbers. Use Case:
grep "error" logfile.txt
Used for general-purpose text searching. Preferred for its balance between speed and flexibility in typical command-line usage.
2. egrep (Extended grep)
Supports extended regular expressions (ERE) without needing the -E flag. Patterns like +, ?, and {} work without escaping. Use Case:
egrep "error|fail|warning" logfile.txt
Preferred when using more complex patterns without the hassle of escaping characters.
3. fgrep (Fixed grep)
Searches for literal strings only, ignoring regular expression syntax. It’s faster for plain-text searches. Use Case:
fgrep "a+b*c" file.txt
Ideal when searching for special characters literally, like +, *, or ..
4. rgrep (Recursive grep)
Recursively searches files in all subdirectories. Equivalent to grep -r. Use Case:
rgrep "TODO" /home/user/projects
Best for scanning through codebases or directory trees for specific terms.
Advanced Grep Usage
Using grep with Regular Expressions
Regular expressions (regex) are special patterns used to match character combinations in text.
grep supports Basic Regular Expressions (BRE) by default and Extended Regular Expressions (ERE) using -E or egrep.
Useful patterns:
^word – matches lines starting with “word”
word$ – matches lines ending with “word”
[0-9]{3} – matches three digits (with -E)
foo|bar – matches “foo” or “bar”
Examples:
grep "^Start" file.txt # Lines starting with "Start"
grep -E "[a-z]{3,5}" file.txt # Words with 3–5 lowercase letters
Piping and Redirection with Grep
grep shines when used in pipelines to filter output from other commands:
Piping: ps aux | grep ssh Filters active processes for SSH-related entries.
This is ideal for log analysis, automation, and chaining commands.
Grep with Wildcards and Patterns
Wildcards (*, ?) are shell-based, not part of grep regex.
* matches any number of characters
? matches a single character
Use wildcards with grep via shell expansion or find:
grep "config" *.txt # Search all .txt files
grep "^[A-Z]" report?.txt # Files like report1.txt, report2.txt
Use Case: grep "function" `find . -name "*.js"` # Search JS files for "function"
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:
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 command. Note 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:
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
Real-World Use Cases for Grep
Grep in System Administration
System administrators rely heavily on grep for monitoring, diagnosing, and maintaining systems. It's a powerful tool for quickly locating issues in vast and complex log files.
Commonly used to search for error messages or patterns in log files: grep "error" /var/log/syslog grep -i "failed" /var/log/auth.log
Useful for checking the status of services: ps aux | grep nginx
In automation scripts, grep helps with on-the-fly diagnostics: if grep -q "disk full" /var/log/dmesg; then echo "Disk issue detected!" fi
Also used to monitor login attempts, search for kernel panics, or filter cron job failures.
With its speed and pattern-matching abilities, grep simplifies system troubleshooting and is essential in any administrator’s toolkit.
Grep for Developers and QA
For developers and QA professionals, grep is indispensable for code navigation, bug tracking, and log analysis.
Quickly locate function definitions or API calls in large codebases: grep "def " *.py # Python functions grep -r "public class" . # Java classes
Search for specific code annotations like TODO, FIXME, or debug messages: grep -r "TODO" . grep "Exception" build.log
QA teams use grep to scan test logs for failures or errors: grep "FAIL" test_output.log
Supports regex-based searches, making it powerful for identifying patterns across multiple files.
In both development and quality assurance workflows, grep speeds up code review, debugging, and verification processes.
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: