Logo

egrep: A Comprehensive Guide With 14 Practical Examples

Try this guide with our instant dedicated server for as low as 40 Euros

Approximately 96.3 percent of the world’s top one million servers run on Linux. Whether you are a seasoned professional or an aspiring sysadmin, several product features can help elevate your server to be among the top one million.

One of these features is the ability to extract patterns from text in files and output streams. You can find several utilities that help you get relevant information from text files. 

grep has been the traditional pattern extraction utility on Linux platforms. However, over time, this utility has fallen short of the users’ expectations. That’s the rationale behind the development of egrep, an improved version of the popular utility. 

In this tutorial, you will learn what egrep is, its syntax, and a few practical examples of how to use egrep for common data extraction tasks.

Let’s start with an overview of the egrep utility.

What is egrep

egrep or Extended Global Regular Expressions Print is a command-line tool used for searching text based on patterns. It is an enhanced version of the grep utility and offers more powerful pattern-matching capabilities.

Here are three features that distinguish egrep from similar utilities:

Extended Regular Expressions

Regular expressions (regex) are special syntaxes (like . *+) for creating patterns to match text. 

Extended regular expressions (EREs) are a more powerful version of basic regex ([],|). Users can define complex search patterns using special characters and go beyond basic string-matching capabilities of grep

Fast Pattern Matching

egrep is known for its speed, especially when compared to the basic grep utility. Command. As a result, egrep can significantly speed up the performance of scripts.

Functionality Similar to grep -E

egrep provides similar functionality as using grep with the -E flag. The -E flag in grep explicitly implies the command to interpret the pattern as an extended regular expression. As a result, you can use the patterns from the grep -E directly into the egrep commands.

Linux egrep Syntax

The basic syntax of the egrep command is as follows:

# egrep [options] pattern [file...]

Here,

  • pattern: This is the regular expression for searching within files. The search pattern must be in quotes if it contains special characters like spaces or metacharacters (*, ? |, etc.).
  • [file…]: This is an optional list of files to search for the pattern. If no files are specified, egrep reads from the standard input.
  • options: These are optional flags that modify egrep’s behavior.

The egrep command in Linux offers a diverse range of options to customize its operation and output. Some of the most commonly used command options are:

                Options                           Descriptions
-i (ignore case) Makes the search case-insensitive, treating uppercase and lowercase letters as equivalent.
-v (invert match) Prints lines that do not match the specified pattern.
-c (count) Count the number of matching lines.
-l (files with matches) Lists filenames with matches without showing the lines.
-L (files without match) Lists filenames with no matches.
-n (line number) Displays line numbers before matching lines.
-o (only matching) Prints only the matched part of the lines.
-q (quiet, silent) Suppresses all normal output; egrep will not display the matching lines. Useful for checking if a pattern exists in files (exiting immediately with zero status if a match is found).
-r or –recursive Searches directories recursively.
-E (extended regular expression) This option is typically redundant with egrep as it already uses extended regular expressions.
-x (line regex) Selects only those that exactly match the entire lines.
-m NUM (max count) Stops reading a file after NUM matches. Useful when you only need a certain number of matches.
-b (byte offset) Prints the byte offset within the input file before each line of output.
-H (with filename) Includes file names in addition to the standard output.
-h (no filename) Suppresses the prefixing of file names on output when multiple files are searched. This is useful when you only need the text matched.
–color=auto (highlight matches) Highlights matching text. This is extremely helpful for quickly identifying matches visually.
B(n) Print (s) the line containing the search term along the n lines before it.
-A(n) Prints n lines after the line with the search string.
-C(n) Prints n lines before and after the line with the search string.

The Prerequisites

Before moving into the practical examples of egrep command, ensure you have the following:

  • A system running a mainstream Linux distribution
  • A text document to test egrep patterns.

14 Examples of egrep Command in Linux

egrep is an extension of grep command, a tool for finding regular expressions and patterns using symbols like ? +, or | as metacharacters. 

Now, let us dive into a few practical examples to showcase the versatility of the egrep command. 

Note: The egrep search feature is case-sensitive, meaning uppercase and lowercase letters are interpreted differently.

Example #1: Basic Search Pattern 

egrep is a command-line utility used for pattern matching using extended regular expressions. It can be used to search for strings in a file.

For instance, let’s say you have a file named example.txt containing the following lines:

This is line 1.

This is line 2.

This is line 3. 

You can use egrep command to search for a string in the file.

  • To search for the string line in the file, run: 

# egrep 'line' example.txt

The command prints every line containing the search string.

This is line 1.

This is line 2.

This is line 3.

egrep 'line' example.txt

  • Now, if you wish to print only the string and not the entire line, use the -o flag: 

# egrep -o line example.txt

The output would only produce the word and not the entire line.

line 

line 

line 

  • Next, combine -o and -b flags to locate matches in a file.

# egrep -b -o line example.txt

By combining these flags, a more precise output that depicts the byte location (specific position) of each match within the line, along with the matched substring itself, will be produced.

egrep -b -o line example.txt

Example#2: Case-Insensitive Search

Now, let’s modify the previous example to perform a case-insensitive search for the word example in the file example.txt. This means it will find Example, EXAMPLE, eXAMPLE, and so on.

  • To perform a case-insensitive search, use the -i flag.

# egrep -i 'example' example.txt

egrep -i 'example' example.txt

Example #3: Find Regular Expressions

The egrep command enables a more complex search with a regular expression. Regular expressions are nothing but a pattern (a sequence of characters) that egrep uses to match each line ro determine whether it should be included in the output. 

For instance, consider the scenario where you have a file named emails.txt that contains the following email addresses:

[email protected]

[email protected]

[email protected]

[email protected]

Now, to find all email addresses ending with @example.com, run this command:

# egrep '[a-zA-Z0-9._%+-]+@example\.com' emails.txt

Here,

  • [a-zA-Z0-9._%+-]+: Creates the patterns that egrep uses to match one or more occurrences of letters (both uppercase and lowercase), digits, dots, underscores, percentage signs, plus signs, and hyphens.
  • @example\.com: Matches the literal string @example.com, where the dot (.) is escaped with a backslash () to treat it as a literal dot.

The output produced would be:

[email protected]

[email protected]

[email protected] 

egrep '[a-zA-Z0-9._%+-]+@example.com

Example #4: Find a Specific Character

You can find a specific character in a text with egrep and bracket expressions. Bracket expressions allow egrep to match the input for the mentioned characters.

Here is a file named passwords.txt containing the following list of passwords. 

mypassword123

secure_password!

weakpassword

strong_password!

Now, you can run the following command to find all passwords that contain the character !:

# egrep '!' passwords.txt

The output of this command will be as follows:

secure_password!

strong_password!

egrep '!' passwords.txt

Example #5: Invert Match in egrep command

The egrep command provides an -v option to invert the match. The -v option provides a powerful way to filter out unwanted information and focus on the specific data within the file(s). 

Let’s say you have a text file named data.txt that contains the following entries:

apple

banana

grape

orange

strawberry

apple pie

cherry 

To filter out any line that contains the word apple, use the egrep command combined with the -v option:

# egrep -v 'apple' data.txt

egrep -v 'apple' data.txt

The command displays all lines that do not include the word apple. 

Example #6: Display Line Numbers

You can use the egrep command combined with the -n flag to display line numbers. The command syntax will be as follows: 

# egrep -n 'example' example.txt

egrep -n 'example' example.txt

Example #7: Recursive Search in a Directory

egrep can search multiple text files to find a specific string.

For instance, you can have a directory named documents containing multiple text files. You can run the following command to search for lines containing the string extended:

# egrep -r 'extended' /var

egrep -r 'extended' var

This command searches for the string extended in all files within the documents directory and its subdirectories. 

Example #8: Count Matching Lines

If you are looking to count the number of lines containing the string example in the file example.txt, use egrep command combined with -c flag. 

You can run the following command to count the number of lines containing the string example in the file.

# egrep -c 'example' example.txt

egrep -c 'example' example.txt

Example #9: Use Pipe For Alternative Matches

The pipe (|) in egrep lets you search for lines matching any possible combination of the search pattern. In practical terms, it acts as an OR operator within the pattern-matching operation.

Consider the data.txt file containing the following data:

apple

banana

grape

orange

strawberry

apple pie

cherry

You can run the following command to find all lines containing apple or orange: 

# egrep 'apple|orange' data.txt

egrep 'appleorange' data.txt

Example #10: Use Ranges in Search Patterns

A hyphen within a bracket expression creates a range expression. 

You can add a pattern within square brackets [] to create a search pattern based on the mentioned range. 

For instance, consider the file named items.txt which contains various alphanumeric codes:

A1

B2

C3

D4

E5

F6

G7

H8

I9

J10

Now, run the following command to find all lines that start with any letter from A to E.

# egrep '^[A-E]' items.txt

egrep '^[A-E]' items.txt

The command utilizes ^ to indicate that the matching must start at the beginning of the line, and [A-E] matches any character in A, B, C, D, or E.

Example #11: Ignore Case (-i)

By default, egrep is case-sensitive and filters results based on the case of the search pattern. You can sidestep this using the -i option to perform a case-insensitive search.

For instance, consider a file named sample.txt that contains the following data:

example

Example

eXample

notanexample

Now, run the following command to search for the word Example in the file:

# egrep -i 'example' sample.txt

The output produced would be:

example

Example

eXample 

Example #12: Print File Names (-l)

In some cases, you only need the files containing the search pattern and not the exact lines from the files. For this, we recommend combining egrep with -l option to print the names of files with matching lines.

Consider the scenario where you have to find the word todo in all .txt files in the current directory. Run the following command to print the file names that contain the matching patterns: 

# egrep -l 'todo' *.txt 

egrep -l 'todo' .txt

Example #13: Find Complete Words Only (-w)

The -w option restricts the search to complete words. This option excludes complete matches in the larger words. For instance, it ignores “fly” in “flywheel”.

Consider the following command to find example as a whole word in document.txt:

# egrep -w 'example' emails.txt

The output of this command will present lines with the word example

[email protected]

[email protected]

[email protected]

[email protected] 

egrep -w 'example' emails.txt

Example #14: Display Lines Before or After the Search String (-B and -A)

You can choose to include additional lines before or after the specific line(s) that matches the search pattern. egrep offers two options for these capabilities:

-B (Before): This option specifies the number of lines to display before each matching line.

-A (After): This option specifies the number of lines to display after each matching line.

Add Lines Before the Match

Consider the file named logs.txt which contains the following content: 

Info: Start process

Warning: Unexpected input

Error: Failed to load module

Info: Process completed

Run the following command to display two lines before each match of the word error in logs.txt:

# egrep -B 2 'Error' logs.txt

The output produced will be:

Info: Start process

Warning: Unexpected input

Error: Failed to load module

egrep -B 2 'Error' logs.txt

Add Lines After the Match

Alternatively, you can run the following command to display one line after each match of start in logs.txt:

# egrep -A 1 'Start' logs.txt 

egrep -A 1 'Start' logs.txt

Conclusion

The egrep command is a powerful tool for searching text using regular expression syntax on Linux or Unix-like systems. It adheres to basic rules that enable users to construct a list of conditions for matching specific patterns within text files.

Through various examples, we’ve demonstrated how egrep enhances the search feature by allowing complex queries that are both flexible and precise.

Whether looking for specific characters, complete words, or complex patterns involving alternatives and ranges, egrep offers a robust solution to navigate and manipulate large datasets efficiently. This makes it an essential tool for system administrators and developers who require precise text-processing capabilities.

FAQs

Q. What are the default options used by egrep for string matching?

The default option egrep focuses primarily on matching patterns without additional formatting or filtering. By default, egrep matches lines with a pattern anywhere in the file without considering case sensitivity or file name display.

Q. How does egrep highlight output when a matching pattern is found?

By default, egrep does not highlight the output. However, in many modern terminal environments or when using grep with –color option, the matching string can be highlighted. For example, egrep –color ‘data’ filename.txt will display data in a different color for better visibility.

Q. Can egrep be used to search for a range expression or a single character?

Yes, egrep supports complex expressions like range expressions. For instance, to find any digits in a text, you can use egrep ‘[0-9]’ file.txt. This command uses a range expression [0-9] to search for any single-digit character.

Q. What does it mean when a character has a special meaning in egrep?

In egrep, some characters have special meanings—these are known as metacharacters. For example, the asterisk * denotes zero or more occurrences of the preceding element. To use such characters as regular characters without their special meaning, you must execute them with a backslash \.

Q. How does egrep handle user input that includes types of regex?

egrep is designed to interpret user input as extended regular expressions (EREs). This means it automatically considers the input to utilize additional metacharacters and capabilities unavailable in basic regex, such as +, ?, {}, |, and parentheses for grouping.

Q. What is the significance of matching complete strings versus string patterns in egrep?

Matching complete strings (using the -w flag) ensures that egrep finds lines containing patterns that form whole words. For example, egrep -w ‘is’ file.txt matches is but not this. In contrast, matching string patterns -w might return any occurrence of the substring.

Q. How can you view the complete list of matches, including previous lines, for context in egrep?

To include context, such as previous lines in your output, you can use the -B option with egrep. For example, egrep -B 1 ‘error’ log.txt shows each match for error along with the line immediately preceding it.

Q. What is the best way for complex pattern searches involving additional metacharacters?

When dealing with complex pattern searches involving additional metacharacters, ensure your regex is correctly formed to account for these elements. For instance, to match an IP address, you might use egrep ‘([0-9]{1,3}\.){3}[0-9]{1,3}’ file.txt. This pattern uses metacharacters for repetition and grouping to accurately define the structure of an IP address.

Try this guide with our instant dedicated server for as low as 40 Euros