Linux logo

What is grep Command in Linux?

The ‘grep’ is a command-line tool that hunts for specific patterns in a designated file. In simple terms, it’s your go-to for searching text.

This mighty command scans a file for lines that match specified words or strings, making it a Linux gem.

With ‘grep,’ you input a text pattern, and it diligently fishes out all the lines harboring that specific pattern or string.

Beyond its text-searching prowess, ‘grep’ unveils its wizardry in the realm of regular expressions.

Think of it as a digital detective that prints out lines matching your defined search pattern. Spice it up with the -color option, and voilà – matching strings pop in vibrant hues.

But what’s the buzz about regular expressions?

They’re the language of search patterns, defining the melody of characters, fixed strings, or complex expressions.

In a nutshell, ‘grep’ and regular expressions together compose a harmonious symphony for unraveling strings and patterns in Linux.

Let’s see how to use grep on a Linux or Unix-like system.

Syntax for using the grep command

grep [-options] pattern filename

The general syntax for using the grep command is providing a word and specifying a file name. For example:

$ grep ‘word_to_search’ filename

You may also specify multiple files:

$ grep ‘text’ file1 file2 file3

Multiple words search

$ grep ‘word1 word2’ filename

The section below shows a few examples of grep command with various options and a little detail wherever required.

An example of searching a file
grep testUsr /etc/passwd
Searching a word in a specified file example

For finding a word in the specified file, you may use a grep command as follows:

$ grep Mango fruits.txt

You may also use fgrep command as well:

$ fgrep Mango fruits.txt
How to use grep recursively

Use the –r option in grep command for searching recursively. The example command below will search in all files for a given string:

$ grep -r "some_text" /etc/
How to find all files with a specific extension

The grep can be extremely helpful for filtering from stdout. For example, let’s say you have an entire folder full of audio files in a whole lot of different formats. You are searching for all the *.mp3 files from the person Haynes, but you do not need any of the tutorial audio files. A find command with a couple of grep pipes will do the trick:

$ find . -name "*.mp3" | grep -i Haynes | grep -vi "tutorial"
Using –w option to search for specified word only

When you search for “text”, grep will fit textdemo, text123, textmore etc.. You can force the grep command to choose only those lines containing matches that form whole words i.e. match just “text” word:

$ grep -w "boo" file
How to use grep to search two Distinct words

An example of searching two words:

$ egrep -w 'string1|string2' /path/to/file
Count Number of Matches example
# ifconfig | grep -c inet6
How to perform case insensitive search

We can force grep to ignore case distinctions in data and patterns. For example, searching for “text” matches Text, texT, TEXT etc.

$ grep -i 'text' /path/to/file
Search Files by Given String

The –n option for grep is quite helpful when debugging files through compile errors. It displays the line number from the file of the specified search string:

$ grep –n "main" setup.py
The –v option example for invert match

If you want to excludet the given word then use the –v option in grep command. For example:

$ grep -v test /path/to/file

$ grep -v '^test' /etc/passwd
Search a string in Gzipped Files using zgrep

The zgrep, a derivative of the grep command, can be used for searching in gzipped files.

Further Reading:  What is Linux ls command?

It takes the same options as grep and can be used in the same manner:

$ zgrep –i error /var/log/syslog.2.gz
UNIX / Linux pipes

The grep command is frequently used with shell pipes. In this example, show the title of the hard disk devices:

$ dmesg | egrep '(s|h)d[a-z]'
What are pipes?

A casing pipe is a way to connect the output of one program to the input of another program with no temporary file.

Display CPU model name:
# cat /proc/cpuinfo | grep -i 'Model'

Best Practices for Using the grep Command in Linux:

  1. Understand the Basics:
    • Grasp the fundamental purpose of the grep command, which is to search for specified patterns in files. It is a powerful tool for text searching in Linux and Unix-like systems.
  2. Learn Regular Expressions:
    • Familiarize yourself with regular expressions (regex) as they define the search patterns for grep. Regular expressions can be simple characters, fixed strings, or complex expressions with special characters.
  3. Syntax Overview:
    • Understand the general syntax of the grep command: grep [-options] pattern filename.
    • Example: $ grep 'word_to_search' filename.
  4. Searching Single and Multiple Files:
    • Use grep to search for a word in a specific file or multiple files.
      • Single File: $ grep 'Mango' fruits.txt
      • Multiple Files: $ grep 'text' file1 file2 file3
  5. Recursive Search:
    • Employ the -r option for recursive searching through directories.
      • Example: $ grep -r "some_text" /etc/
  6. Filtering with find and grep:
    • Utilize the combination of find and grep to filter files based on specific criteria.
      • Example: $ find . -name "*.mp3" | grep -i Haynes | grep -vi "tutorial"
  7. Whole Word Search:
    • Use the -w option to search for a specified word only, excluding partial matches.
      • Example: $ grep -w "boo" file
  8. Search for Two Distinct Words:
    • For searching two different words, utilize egrep with the pattern ‘word1|word2’.
      • Example: $ egrep -w 'string1|string2' /path/to/file
  9. Count Number of Matches:
    • Use the -c option to count the number of matches, providing a quick summary.
      • Example: # ifconfig | grep -c inet6
  10. Case Insensitive Search:
    • Make searches case insensitive using the -i option to match patterns regardless of case distinctions.
      • Example: $ grep -i 'text' /path/to/file
  11. Display Line Numbers:
    • Include the -n option to display line numbers of matched strings for effective debugging.
      • Example: $ grep -n "main" setup.py
  12. Invert Match with -v Option:
    • Exclude specific words by using the -v option to invert the match.
      • Example: $ grep -v 'test' /path/to/file
  13. Search in Gzipped Files with zgrep:
    • When dealing with gzipped files, use zgrep for searching. It supports the same options as grep.
      • Example: $ zgrep -i error /var/log/syslog.2.gz
  14. Utilize Pipes for Efficiency:
    • Leverage Unix pipes (|) to connect the output of one command to the input of another, enhancing the efficiency of commands.
      • Example: $ dmesg | egrep '(s|h)d[a-z]'

Understanding and incorporating these best practices will enhance your proficiency with the grep command, making text searches in Linux more effective and streamlined.

Further Reading:  The echo Command in Linux

Frequently Asked Questions (FAQs) about the grep Command:

1. What is the primary purpose of the grep command?

  • The grep command is used to search for specified patterns in files. It scans text for lines containing a match to the specified words or strings.

2. How does grep handle pattern matching?

  • Fundamentally, grep allows users to input a pattern of text, and it searches for this pattern within the provided text. It returns all lines containing the specified pattern or string.

3. What are regular expressions, and how are they related to grep?

  • Regular expressions (regex) define search patterns for strings. In the context of grep, regular expressions can be simple characters, fixed strings, or complex expressions containing special characters describing the pattern.

4. What is the syntax for using the grep command?

  • The general syntax is: grep [-options] pattern filename. For example: $ grep 'word_to_search' filename. Multiple files and multiple words can also be specified in the command.
Further Reading:  Create New Directory in Linux/Unix by mkdir

5. How can I perform a recursive search using grep?

  • Use the -r option in the grep command for searching recursively. Example: $ grep -r "some_text" /etc/.

6. How can I find all files with a specific extension using grep?

  • grep can be combined with the find command for such tasks. Example: $ find . -name "*.mp3" | grep -i Haynes | grep -vi "tutorial".

7. What does the -w option do in grep?

  • The -w option forces grep to search for whole words only. It ensures that matches form complete words and not substrings. Example: $ grep -w "boo" file.

8. How do I search for two distinct words using grep?

  • Utilize egrep with the pattern ‘word1|word2’. Example: $ egrep -w 'string1|string2' /path/to/file.

9. How can I count the number of matches with grep?

  • Use the -c option to count the number of matches. Example: # ifconfig | grep -c inet6.

10. How do I perform a case-insensitive search with grep? – Use the -i option to ignore case distinctions. Example: $ grep -i 'text' /path/to/file.

11. What does the -n option in grep do? – The -n option displays line numbers along with the matched strings. Useful for debugging. Example: $ grep -n "main" setup.py.

12. How can I invert the match using the -v option in grep? – The -v option excludes lines containing the specified word. Example: $ grep -v test /path/to/file.

13. How can I search in gzipped files using zgrep?zgrep is a derivative of grep for searching in gzipped files. Example: $ zgrep -i error /var/log/syslog.2.gz.

14. What is the purpose of using pipes (|) with grep in Linux? – Pipes connect the output of one program to the input of another without using temporary files. Example: $ dmesg | egrep '(s|h)d[a-z]'.

15. How can I find the CPU model name using grep with pipes? – Example: # cat /proc/cpuinfo | grep -i 'Model'. This command extracts and displays the CPU model name from the system information.**