How to Use the egrep Command in Linux

Updated on October 11, 2024
How to Use the egrep Command in Linux header image

Introduction

The egrep (Extended Global Regular Expression Print) command in Linux is a powerful text searching tool for advanced pattern matching using extended regular expressions (ERE). egrep is part of the grep family of commands which include grep and fgrep. egrep supports extended regular expressions unlike grep making it more versatile for complex pattern matching.

This article explains how to use the egrep command in Linux to efficiently match patterns and perform file search tasks.

Understand Regular Expressions

Regular expressions (regex) are sequences of characters that form search patterns. Regex searches specific keywords or strings using multiple characters and special symbols. egrep utilizes the following extended regular expression symbols to form search patterns with additional features:

  • Anchors: Match the start (^) or end ($) of a line. For example, ^error.
  • Character Classes: Match any character within brackets ([ ]). For example, [a-z].
  • Repetition: Matches characters with zero or more (*), one or more (+), or zero or one (?) occurrences. For example, a*, a+, a?.
  • Alternation: Finds a match between two or more possibilities (|). For example: error|warning.
  • Grouping: Groups patterns using parentheses (( )). For example, (error|warning).
  • Word Boundaries: Match whole keywords only (\b). For example, \berror\b.
  • Line Boundaries: Match whole lines only (^pattern$). For example, ^error$.

Differentiate Between BRE and ERE

  • BRE: grep (BRE) escapes certain metacharacters to use their special meaning, such as \+ or \?. For example, to search for one or more occurrences of the letter a in a file, use the + symbol to form the command grep 'a\+' file.txt.

  • ERE: egrep (ERE) metacharacters (+, ?, |) and parentheses () do not require escaping, making the syntax cleaner and more intuitive for complex patterns. For example, you can use the same grep character without escaping in egrep to form the command egrep 'a+' file.txt.

The Basic egrep Command Syntax

The egrep command uses the following command syntax:

egrep [options] 'pattern' [file...]

In the above command:

  • [options]: Include optional flags that modify the command's behavior.
  • 'pattern': Defines the pattern that you want to find.
  • [file...]: Specifies the file you want to search.

Set Up Example Directories and Files

Follow the steps below to create example directories and files to test the egrep command.

  1. Switch to your user's home directory.

    console
    $ cd
    
  2. Create the vultr.txt, Vultr.txt, and VULTR.txt files in your working directory.

    console
    $ touch vultr.txt Vultr.txt VULTR.txt
    
  3. Create two directories and a subdirectory.

    console
    $ mkdir -p dir dir1/sub_dir
    

    The above command creates the dir directory and the sub_dir subdirectory under dir1. The -p option creates the parent directory if it does not exist.

  4. Create a new sample vultr.txt file using a text editor like nano.

    console
    $ nano vultr.txt
    
  5. Add the following contents to the file.

    Vultr
    Hello World, Greetings from Vultr! This is file number 1
    Example text, greetings from vultr!
    Example text, greetings from VULTR!
    Number of data centers: 25+ locations worldwide
    Number of server plans: Over 20 different plans
    CPU cores: From 1 to 64 cores
    RAM: From 512MB to 256GB
    Storage: SSD storage up to 10TB
    Average uptime: 99.9%

    Save and close the file.

Use Most Common egrep Command Options

The following list displays the most common egrep command options:

Option Description
-i Ignore case (case-insensitive search)
-v Invert the match (show lines that do not match the pattern)
-c Display the count of matching lines
-n Show line numbers along with the matching lines
-l List only the names of files with matches
-r Recursively search directories
-w Match whole keywords only
-x Match entire lines only
--color Highlight matched patterns in color
-A n Display n lines of context after each match
-B n Display n lines of context before each match
-C n Display n lines of context around each match

Use Practical egrep Command in Linux with Example

Follow the steps below to use the egrep command with practical examples.

  1. Perform a basic pattern search for all lines that contain the Vultr keyword in the vultr.txt file.

    console
    $ egrep 'Vultr' vultr.txt
    

    Output:

    basic pattern match

  2. Highlight the color of the Vultr keyword using the --color option.

    console
    $ egrep --color=auto 'Vultr' vultr.txt
    

    Output:

    highlight search keyword

  3. Search for lines that contain the vultr keyword regardless of the case sensitivity.

    console
    $ egrep -i 'vultr' vultr.txt
    

    The above command searches for the vultr keyword in vultr.txt and displays all results that match any case, ignoring case sensitivity. For example, vultr, Vultr, and VULTR match the search.

    Output:

    case-insensitive search

  4. Run an inverted search to find the lines that do not contain the vultr keyword .

    console
    $ egrep -v 'vultr' vultr.txt
    

    Output:

    inverted match

  5. Count the matching lines containing the Vultr keyword.

    console
    $ egrep -c 'Vultr' vultr.txt
    

    Output:

    count matching lines

  6. Display lines that contain the Vultr keyword along with the respective line numbers.

    console
    $ egrep -n 'Vultr' vultr.txt
    

    Output:

    display line numbers

  7. Search multiple files to find lines that contain the Vultr keyword.

    console
    $ egrep 'Vultr' vultr.txt Vultr.txt
    

    Output:

    search multiple files

  8. Recursively search for lines that contain the Hello keyword in a directory.

    console
    $ egrep -r 'Hello' /home/vultr_user/dir1
    

    The above command searches for the Hello keyword in all files within the /home/vultr_user/dir1 directory and subdirectories.

    Output:

    recursive directory search

  9. Display the context before the Number keyword .

    console
    $ egrep -B 2 -n 'Number' vultr.txt
    

    The above command displays two lines of context before each matching line that contains the Number keyword in vultr.txt along with the line numbers.

    Output:

    display context before match

  10. Display the context after the Number keyword .

    console
    $ egrep -A 2 -n 'Number' vultr.txt
    

    The above command displays two lines of context after each matching line that contains the Number keyword in the vultr.txt file along with the line numbers.

    Output:

    display context after match

  11. Display the context around the Number keyword.

    console
    $ egrep -C 2 -n 'Number' vultr.txt
    

    The above command displays two lines of context before and after each matching line that contains the Number keyword in vultr.txt file.

    Output:

    display context around match

Use Advanced egrep Command Options

Follow the steps below to use the advanced egrep command options.

  1. Search for lines containing Example followed by the from keywords using group search.

    console
    $ egrep '(Example.*from)' vultr.txt
    

    The above command searches for lines in vultr.txt where any characters follow the Example keyword and then the from keyword .

    Output:

    grouping and matching

  2. Search for lines that contain the full vultr keyword.

    console
    $ egrep -w 'vultr' vultr.txt
    

    The above command searches for lines in vultr.txt that contain vultr as a full term and not as part of another keyword like vultrs.

    Output:

    match whole keyword

  3. Search for lines that exactly match Vultr.

    console
    $ egrep -x 'Vultr' vultr.txt
    

    The above command searches for lines in vultr.txt that match the Vultr keyword without any additional characters.

    Output:

    exact match

Use Regular Expressions with the egrep Command in Linux

Follow the steps below to use regular expressions with the egrep command to filter the search results.

  1. Create a sample.txt file.

    console
    $ nano sample.txt
    
  2. Add the following contents to the sample.txt file.

    error occurred at 10:45
    warning: disk space is low
    all systems operational
    warning logs updated at 09:00
    log entry recorded
    this is just an error logs
    error
    success
    network issues at 12:30

    Save and close the file.

  3. Anchors: Match the start ^ or end $ of a line.

    • Search for lines in a log file that start with the error keyword.

      console
      $ egrep '^error' sample.txt
      

      The above pattern matches all lines that begin with the error keyword. If a line starts with another term, that match fails.

      Output:

      anchor start search

    • Search for lines in a file that end with the success keyword.

      console
      $ egrep 'success$' sample.txt
      

      The above pattern matches all lines that end with the success keyword. Any line with additional characters at the end fails the match.

      Output:

      anchor end search

  4. Character Classes: Match any character in brackets [ ].

    • Search for any line that contains lowercase letters between a and f.

      console
      $ egrep '[a-f]' sample.txt
      

      The above pattern matches any lowercase letter from a to f to return lines that contain at least any of the characters.

      Output:

      character class match

    • Search for lines with numeric values.

      console
      $ egrep '[0-9]' sample.txt
      

      The above pattern matches any digit from 0 to 9 and displays all lines that contain numeric values.

      Output:

      numeric match

  5. Repetition: Match a keyword with zero or more *, one or more +, or zero or one ? occurrences.

    • Search for lines with zero or more occurrences of the a keyword.

      console
      $ egrep 'a*' sample.txt
      

      Output:

      zero or more match

    • Search for lines with one or more occurrences of the a keyword.

      console
      $ egrep 'a+' sample.txt
      

      Output:

      one or more match

    • Search for lines that contain the logs keyword followed by an optional s (to match both log and logs) in the sample.txt file.

      console
      $ egrep 'logs?' sample.txt
      

      The above pattern matches all lines that contain log or logs. The (?) question mark symbol makes the s character optional.

      Output:

      optional s match

  6. Alternation: Match either pattern using the | pipe symbol.

    • Search for lines that contain either error or warning.

      console
      $ egrep 'error|warning' sample.txt
      

      The above pattern matches all lines that contain either the error or warning keywords.

      Output:

      alternation search

  7. Grouping: Match group patterns using parenthesis ( ).

    • Search for lines that contain either the error or warning followed by the log keywords.

      console
      $ egrep '(error|warning) log' sample.txt
      

      Output:

      grouping search

  8. Word Boundaries: Match whole words only using \b.

    • Search for lines that include error as a complete keyword and not a part of another keyword such as errors.

      console
      $ egrep '\berror\b' sample.txt
      

      Output:

      keyword boundary match

  9. Line Boundaries: Match whole lines only using ^pattern$.

    • Perform an exact search for lines that contain the error keyword without any additional text.

      console
      $ egrep '^error$' sample.txt
      

      Output:

      exact line match

Combine egrep with Other Commands

  1. Use egrep with pipe to filter the output of another command as the egrep input. For example, run the following command to find lines that contain the data keyword in the ps aux command output.

    console
    $ ps aux | egrep 'data'
    

    Output:

    egrep with pipe

  2. Combine egrep with find to search for patterns in files listed by find. For example, run the following command to search for the Hello keyword in all .txt files in a directory.

    console
    $ find /home/vultr_user/dir1 -name "*.txt" -exec egrep 'Hello' {} \;
    

    The above find command searches all .txt files in the /home/vultr_user/dir1 directory and its subdirectories. Then, egrep searches for the Hello keyword in the files.

    Output:

    egrep with find

  3. Combine egrep with xargs for a more efficient search. For example, search for the Hello keyword in all .txt files in a directory.

    console
    $ find /home/vultr_user/dir1 -name "*.txt" | xargs egrep 'Hello'
    

    The above command finds all .txt files in the /home/vultr_user/dir1 directory and passes the output to egrep to search for the Hello keyword. xargs improves efficiency by passing multiple files to egrep in a single command.

    Output:

    egrep with xargs

  4. Combine egrep with wc command.

    console
    $ egrep -o 'Vultr' vultr.txt | wc -l
    

    The above command counts the number of times the Vultr keyword appears in the vultr.txt file. The -o option instructs egrep to print only the matching parts while wc -l counts the number of lines in the search results.

    Output:

    egrep with wc

Use Additional egrep Command in Linux with Examples

  1. Search for lines that contain either the Greetings or the Vultr keywords from the vultr.txt file in a case-insensitive manner and display line numbers.

    console
    $ egrep -in 'Greetings|Vultr' vultr.txt
    

    Output:

    case-insensitive search with line numbers

  2. Count the number of lines that contain the vultr keyword and display the matching lines.

    console
    $ egrep -c 'vultr' vultr.txt && egrep 'vultr' vultr.txt
    

    Output:

    count and display matching lines

Conclusion

You have used the egrep command in Linux with practical examples, options, and syntax to search files for specific contents. egrep supports extended regular expressions making it suitable for a wide range of pattern-matching tasks. You can use egrep effectively for basic searches or complex text-processing tasks by integrating it with other Linux commands. For more information, run man egrep to view the command's manual page.