The Wayback Machine - https://web.archive.org/web/20250306022506/https://www.geeksforgeeks.org/grep-command-in-unixlinux/
Open In App

grep command in Unix/Linux

Last Updated : 12 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

grep command in Unix/Linux – FAQs

What is grep command on Linux?

grep searches the input files for lines containing a match to a given pattern list. When it finds a match, it outputs the line or can perform other specified actions. It’s incredibly useful for searching through large logs, files, or command outputs to find specific information.

How to run a grep command in Unix?

To run grep in Unix, you can use the following basic syntax:

grep [options] pattern [file...]

For example, to search for the word “error” in a file called log.txt, you would use:

grep "error" log.txt

Why grep is used in Unix?

grep is used in Unix for a variety of reasons, such as:

  • Searching for specific patterns within files.
  • Filtering output of other commands.
  • Checking for the presence of certain data within databases or logs.
  • Automating tasks in scripts that depend on the presence or absence of specified data.

What is the grep -R command in Unix?

The -R option in grep stands for recursive. When this option is used, grep will search through all directories and subdirectories starting from the given directory and perform the search operation. For example:

grep -R "search_term" /path/to/directory/

This command will search for “search_term” in all files located within the specified directory and all its subdirectories.

How to use grep to find a word?

To use grep to find a specific word in a file, you can simply pass the word as the pattern, and grep will print out every line in the file that contains that word. For instance:

grep "example" filename.txt

This will search for the word “example” in filename.txt and display all lines containing that word.

Additionally, if you want to ensure that grep matches only whole words, you can use the -w flag:

grep -w "example" filename.txt

Master DevOps and also get 90% Course fee refund on completing 90% course in 90 days! Take the Three 90 Challenge today.

The most sought-after Three 90 challenge has started and this is your chance to upskill and get 90% refund. What more motivation do you need? Start the challenge right away!


Next Article

Similar Reads

Difference between grep and fgrep command
This is the powerful grep and fgrep commands used to search text in a Linux-based system. Despite their similarity in use, which is for matching patterns in file strings, they still appear to be different in their own approach and capabilities. Grep supports regular expressions, including flexible and complex patterns of searching, whereas fgrep, s
4 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 accord
4 min read
Extract Emails From a Text File Using Grep Command in Linux
When dealing with large text files containing various information, it's often necessary to extract specific data such as email addresses. While manual extraction is possible, it can be time-consuming and error-prone. This is where the powerful grep command in Linux comes to our rescue. In this article, we'll explore how to use grep to efficiently e
4 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
grep command in Unix/Linux
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 ali
7 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
How to Recursively Grep all Directories and Subdirectories in Linux
The grep command is one of the most frequently used utilities in Linux for searching through text files. It allows users to search for specific strings within files and directories, offering a wide range of options to customize the search process. In this article, we’ll explore how to use the recursive option of grep to search through directories a
5 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 mat
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