Lesson 28: egrep Command
In this lesson, you'll learn how to use the egrep command to search for extended regular expression patterns in files in Linux.
egrep Command: A powerful tool for searching text using extended regular expressions.Linux provides various text-filtering utilities such as awk, sed, cut, etc. However, egrep is one of the most powerful and commonly used utilities for text processing in Linux.
The egrep command in Linux is recognized by the family of the grep command, which is used for searching and matching a particular pattern in files.
It works similarly to grep -E (grep Extended regex), But it mostly searches a particular file or even line by line, or prints the line in the given file.
egrep Command Syntax
The syntax of the egrep command is as follows:
$ egrep [OPTIONS] PATTERNS [FILES]
egrep Command Options
| Option | Description |
|---|---|
--color |
Highlight the matched pattern in color |
-c |
Count the number of matching lines |
-o |
Print only the matched part of each line |
-i |
Case-insensitive pattern matching |
-w |
Match whole words only |
-v |
Invert match - print lines that do NOT match |
-n |
Display line numbers with matching lines |
-q |
Quiet mode - do not print output, only return exit status |
-B N |
Print N lines before the matching line |
-A N |
Print N lines after the matching line |
-C N |
Print N lines before and after the matching line |
-r |
Search recursively in all subdirectories |
Let's discuss some of the practical examples of the egrep command.
Before proceeding, create a sample text file with the following contents, which we will use as an example:
$ cat sample.txt
TecMint is the best Linux resource website on the internet.
We have been publishing Linux tutorials and articles since 2012.
TecMint was started on 15th August 2012 by technical professionals and all the
articles and contents are written by talented professionals around the globe.
The website covers topics like Linux commands, shell scripting, and more.
Users can visit our web portal and find useful Linux commands.
We were glad to help Linux users worldwide.
Here, we can see that the text file is ready. Now, let's discuss a few common examples that can be used on a daily basis.
1. Find a Pattern in a Single File
Let's start with a simple pattern-matching example, where we can use the command below to search for the string professionals in the sample.txt file:
$ egrep professionals sample.txt
TecMint was started on 15th August 2012 by technical professionals and all the
articles and contents are written by talented professionals around the globe.
Here, we can see that the command prints the lines that contain the specified pattern.