Open In App

grep command in Unix/Linux

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The grep command in Unix/Linux is a powerful tool used for searching and manipulating text patterns within files. Its name is derived from the ed (editor) command g/re/p (globally search for a regular expression and print matching lines), which reflects its core functionality. grep is widely used by programmers, system administrators, and users alike for its efficiency and versatility in handling text data. In this article, we will explore the various aspects of the grep command.

Syntax of grep Command in Unix/Linux

The basic syntax of the `grep` command is as follows:

grep [options] pattern [files]



Here,

[options]: These are command-line flags that modify the behavior of grep

[pattern]: This is the regular expression you want to search for.

[file]: This is the name of the file(s) you want to search within. You can specify multiple files for simultaneous searching.

Options Available in grep Command

Options

Description

-c

This prints only a count of the lines that match a pattern

-h

Display the matched lines, but do not display the filenames.

i

Ignores, case for matching

-l

Displays list of a filenames only.

-n

Display the matched lines and their line numbers.

-v

This prints out all the lines that do not matches the pattern

-e exp

Specifies expression with this option. Can use multiple times.

-f file

Takes patterns from file, one per line.

-E

Treats pattern as an extended regular expression (ERE)

-w

Match whole word

-o

Print only the matched parts of a matching line, with each such part on a separate output line.

-A n

Prints searched line and nlines after the result.

-B n

Prints searched line and n line before the result.

-C n

Prints searched line and n lines after before the result.

Sample Commands

Consider the below file as an input. 

cat > geekfile.txt

unix is great os. unix was developed in Bell labs.

learn operating system.

Unix linux which one you choose.

uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

Pratical Example of grep Command in Linux

The -i option enables to search for a string case insensitively in the given file. It matches the words like “UNIX”, “Unix”, “unix”. 

grep -i "UNix" geekfile.txt

Output: 

Case insensitive search

Case insensitive search

2. Displaying the Count of Number of Matches Using grep

We can find the number of lines that matches the given string/pattern 

grep -c "unix" geekfile.txt

Output: 

Displaying the count number of the matches

Displaying the count number of the matches

3. Display the File Names that Matches the Pattern Using grep

We can just display the files that contains the given string/pattern. 

grep -l "unix" *

or

grep -l "unix" f1.txt f2.txt f3.xt f4.txt

Output: 

The file name that matches the pattern

The file name that matches the pattern

4. Checking for the Whole Words in a File Using grep

By default, grep matches the given string/pattern even if it is found as a substring in a file. The -w option to grep makes it match only the whole words. 

grep -w "unix" geekfile.txt

Output: 

checking whole words in a file

checking whole words in a file

5. Displaying only the matched pattern Using grep

By default, grep displays the entire line which has the matched string. We can make the grep to display only the matched string by using the -o option. 

grep -o "unix" geekfile.txt

Output: 

Displaying only the matched pattern

Displaying only the matched pattern

6. Show Line Number While Displaying the Output Using grep -n

To show the line number of file with the line matched. 

grep -n "unix" geekfile.txt

Output: 

Show line number while displaying the output

Show line number while displaying the output

7. Inverting the Pattern Match Using grep

You can display the lines that are not matched with the specified search string pattern using the -v option. 

grep -v "unix" geekfile.txt


Output: 

Inverting the pattern match

Inverting the pattern match

8. Matching the Lines that Start with a String Using grep

The ^ regular expression pattern specifies the start of a line. This can be used in grep to match the lines which start with the given string or pattern. 

grep "^unix" geekfile.txt

Output: 

Matching the lines that start with a string

Matching the lines that start with a string

9. Matching the Lines that End with a String Using grep

The $ regular expression pattern specifies the end of a line. This can be used in grep to match the lines which end with the given string or pattern. 

grep "os$" geekfile.txt

10.Specifies expression with -e option

Can use multiple times : 

grep –e "Agarwal" –e "Aggarwal" –e "Agrawal" geekfile.txt


11. -f file option Takes patterns from file, one per line

cat pattern.txt

Agarwal
Aggarwal
Agrawal

grep –f pattern.txt  geekfile.txt


12. Print n Specific Lines from a File Using grep

-A prints the searched line and n lines after the result, -B prints the searched line and n lines before the result, and -C prints the searched line and n lines after and before the result. 

Syntax:

grep -A[NumberOfLines(n)] [search] [file]  

grep -B[NumberOfLines(n)] [search] [file]  

grep -C[NumberOfLines(n)] [search] [file]  


Example:

grep -A1 learn geekfile.txt


Output:  

Print n specific lines from a file

Print n specific lines from a file

13. Search Recursively for a Pattern in the Directory

-R prints the searched pattern in the given directory recursively in all the files.

Syntax:

grep -R [Search] [directory]


 Example :

grep -iR geeks /home/geeks


Output:

./geeks2.txt:Well Hello Geeks
./geeks1.txt:I am a big time geek
----------------------------------
-i to search for a string case insensitively
-R to recursively check all the files in the directory.



Conclusion

In this article we discussed the grep command in Linux which is a powerful text-search tool that uses regular expressions to find patterns or text within files. It offers various options like case insensitivity, counting matches, and listing file names. With the ability to search recursively, use regular expression flags, and customize output, grep is a vital tool for Linux users to efficiently handle text-related tasks. Mastering grep enhances your ability to work with text data in the Linux environment.



Previous Article
Next Article

Similar Reads

Difference between grep and fgrep command
The grep filter searches a file for a particular pattern of characters and displays all lines that contain that pattern. The fgrep filter searches for fixed-character strings in a file or files. Syntax of grep command: grep [options] pattern [files] Syntax of fgrep command: fgrep [options] pattern [files] The main difference between both commands i
2 min read
Shell Script to Display the Exit Status Using Grep Command
Linux provides users a great cool feature of the command-line tool along with a graphical user interface where they can perform tasks via ruining command. All of this command returns a status according to their execution. Its execution value can be used for showing errors or take some other action in a shell script. Exit status is following accordi
4 min read
Extract Emails From a Text File Using Grep Command in Linux
Let's consider we have a text file that contains lots of text and in that text file there are some email IDs present, and we have to find the all email IDs present in that text file. So what we can do? How can we find all email IDs present in that text file?. One way to find all email IDs manually, but this is a very time-consuming and boring proce
3 min read
Run a Command Conditionally with netcat and grep
In this article, we will explore the combination of Netcat (nc) and Grep commands in a Unix-like environment to execute commands conditionally based on specific search criteria. Netcat enables network communication, serving as a tool for sending and receiving data across networks. Meanwhile, Grep excels at pattern matching within textual data. By i
4 min read
Check If File Exist Inside Tar File Using Tar And Grep Command
Linux users are familiar with the popular command-line tool Tar (tape archive), which is used to archive directories and files into a single file called a "tarball." Occasionally, you might need to verify whether a certain file is present in a tar archive without extracting the full archive. This detailed article will show you how to effectively se
4 min read
How to Recursively Grep all Directories and Subdirectories in Linux
In this article, we will demonstrate how to grep recursively through all directories and subdirectories. But before I do that, let me define what the term "grep" means. Basically, grep means searching or fetching. The grep is one of the basic utility commands of Linux systems. When one needs to determine whether a specific string is present in a te
3 min read
How to suppress binary file matching results in grep
In this article, we will discuss the topic of grep. Also, we will discuss what are the problems that occurred during binary files while using the grep command. Lastly, we will discuss how we can solve this problem using grep options. Grep The grep, Global Regular Expression Print is a command line utility that is used to print the string after matc
3 min read
How To Show Only Filenames with grep on Linux
In Linux, the 'grep' command is one of the most used commands by many administrators to perform the advanced search of text within the files. Grep is one of the important text-search commands in Unix-based operating systems. Along with this, we can also use this command to filter and simultaneously display the list or the directories preset on our
5 min read
Regular Expression in grep
Prerequisite: grep Basic Regular Expression Regular Expression provides an ability to match a "string of text" in a very flexible and concise manner. A "string of text" can be further defined as a single character, word, sentence or particular pattern of characters. Like the shell’s wild–cards which match similar filenames with a single expression,
3 min read
Shell Script for grep with context display and highlighted pattern matches
grep ( global search for regular expression and print out ) is a filtering command used for searching a particular pattern of characters in a file. It offers different options for manipulating the searched result, a brief description of these options can be found in this article. General Syntax :$ grep [option(s)] pattern [file(s)] One of the optio
4 min read