
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 letterain a file, use the+symbol to form the commandgrep '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 samegrepcharacter without escaping inegrepto form the commandegrep '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.
Switch to your user's home directory.
console$ cd
Create the
vultr.txt,Vultr.txt, andVULTR.txtfiles in your working directory.console$ touch vultr.txt Vultr.txt VULTR.txt
Create two directories and a subdirectory.
console$ mkdir -p dir dir1/sub_dir
The above command creates the
dirdirectory and thesub_dirsubdirectory underdir1. The-poption creates the parent directory if it does not exist.Create a new sample
vultr.txtfile using a text editor likenano.console$ nano vultr.txt
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.
Perform a basic pattern search for all lines that contain the
Vultrkeyword in thevultr.txtfile.console$ egrep 'Vultr' vultr.txt
Output:

Highlight the color of the
Vultrkeyword using the--coloroption.console$ egrep --color=auto 'Vultr' vultr.txt
Output:

Search for lines that contain the
vultrkeyword regardless of the case sensitivity.console$ egrep -i 'vultr' vultr.txt
The above command searches for the
vultrkeyword invultr.txtand displays all results that match any case, ignoring case sensitivity. For example,vultr,Vultr, andVULTRmatch the search.Output:

Run an inverted search to find the lines that do not contain the
vultrkeyword .console$ egrep -v 'vultr' vultr.txt
Output:

Count the matching lines containing the
Vultrkeyword.console$ egrep -c 'Vultr' vultr.txt
Output:

Display lines that contain the
Vultrkeyword along with the respective line numbers.console$ egrep -n 'Vultr' vultr.txt
Output:

Search multiple files to find lines that contain the
Vultrkeyword.console$ egrep 'Vultr' vultr.txt Vultr.txt
Output:

Recursively search for lines that contain the
Hellokeyword in a directory.console$ egrep -r 'Hello' /home/vultr_user/dir1
The above command searches for the
Hellokeyword in all files within the/home/vultr_user/dir1directory and subdirectories.Output:

Display the context before the
Numberkeyword .console$ egrep -B 2 -n 'Number' vultr.txt
The above command displays two lines of context before each matching line that contains the
Numberkeyword invultr.txtalong with the line numbers.Output:

Display the context after the
Numberkeyword .console$ egrep -A 2 -n 'Number' vultr.txt
The above command displays two lines of context after each matching line that contains the
Numberkeyword in thevultr.txtfile along with the line numbers.Output:

Display the context around the
Numberkeyword.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
Numberkeyword invultr.txtfile.Output:

Use Advanced egrep Command Options
Follow the steps below to use the advanced egrep command options.
Search for lines containing
Examplefollowed by thefromkeywords using group search.console$ egrep '(Example.*from)' vultr.txt
The above command searches for lines in
vultr.txtwhere any characters follow theExamplekeyword and then thefromkeyword .Output:

Search for lines that contain the full
vultrkeyword.console$ egrep -w 'vultr' vultr.txt
The above command searches for lines in
vultr.txtthat containvultras a full term and not as part of another keyword likevultrs.Output:

Search for lines that exactly match
Vultr.console$ egrep -x 'Vultr' vultr.txt
The above command searches for lines in
vultr.txtthat match theVultrkeyword without any additional characters.Output:

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.
Create a
sample.txtfile.console$ nano sample.txt
Add the following contents to the
sample.txtfile.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:30Save and close the file.
Anchors: Match the start
^or end$of a line.Search for lines in a log file that start with the
errorkeyword.console$ egrep '^error' sample.txt
The above pattern matches all lines that begin with the
errorkeyword. If a line starts with another term, that match fails.Output:

Search for lines in a file that end with the
successkeyword.console$ egrep 'success$' sample.txt
The above pattern matches all lines that end with the
successkeyword. Any line with additional characters at the end fails the match.Output:

Character Classes: Match any character in brackets
[ ].Search for any line that contains lowercase letters between
aandf.console$ egrep '[a-f]' sample.txt
The above pattern matches any lowercase letter from
atofto return lines that contain at least any of the characters.Output:

Search for lines with numeric values.
console$ egrep '[0-9]' sample.txt
The above pattern matches any digit from
0to9and displays all lines that contain numeric values.Output:

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
akeyword.console$ egrep 'a*' sample.txt
Output:

Search for lines with one or more occurrences of the
akeyword.console$ egrep 'a+' sample.txt
Output:

Search for lines that contain the
logskeyword followed by an optionals(to match bothlogandlogs) in thesample.txtfile.console$ egrep 'logs?' sample.txt
The above pattern matches all lines that contain
logorlogs. The (?) question mark symbol makes thescharacter optional.Output:

Alternation: Match either pattern using the
|pipe symbol.Search for lines that contain either
errororwarning.console$ egrep 'error|warning' sample.txt
The above pattern matches all lines that contain either the
errororwarningkeywords.Output:

Grouping: Match group patterns using parenthesis
( ).Search for lines that contain either the
errororwarningfollowed by thelogkeywords.console$ egrep '(error|warning) log' sample.txt
Output:

Word Boundaries: Match whole words only using
\b.Search for lines that include
erroras a complete keyword and not a part of another keyword such aserrors.console$ egrep '\berror\b' sample.txt
Output:

Line Boundaries: Match whole lines only using
^pattern$.Perform an exact search for lines that contain the
errorkeyword without any additional text.console$ egrep '^error$' sample.txt
Output:

Combine egrep with Other Commands
Use
egrepwithpipeto filter the output of another command as theegrepinput. For example, run the following command to find lines that contain thedatakeyword in theps auxcommand output.console$ ps aux | egrep 'data'
Output:

Combine
egrepwithfindto search for patterns in files listed byfind. For example, run the following command to search for theHellokeyword in all.txtfiles in a directory.console$ find /home/vultr_user/dir1 -name "*.txt" -exec egrep 'Hello' {} \;
The above
findcommand searches all.txtfiles in the/home/vultr_user/dir1directory and its subdirectories. Then,egrepsearches for theHellokeyword in the files.Output:

Combine
egrepwithxargsfor a more efficient search. For example, search for theHellokeyword in all.txtfiles in a directory.console$ find /home/vultr_user/dir1 -name "*.txt" | xargs egrep 'Hello'
The above command finds all
.txtfiles in the/home/vultr_user/dir1directory and passes the output toegrepto search for theHellokeyword.xargsimproves efficiency by passing multiple files toegrepin a single command.Output:

Combine
egrepwithwccommand.console$ egrep -o 'Vultr' vultr.txt | wc -l
The above command counts the number of times the
Vultrkeyword appears in thevultr.txtfile. The-ooption instructsegrepto print only the matching parts whilewc -lcounts the number of lines in the search results.Output:

Use Additional egrep Command in Linux with Examples
Search for lines that contain either the
Greetingsor theVultrkeywords from thevultr.txtfile in a case-insensitive manner and display line numbers.console$ egrep -in 'Greetings|Vultr' vultr.txt
Output:

Count the number of lines that contain the
vultrkeyword and display the matching lines.console$ egrep -c 'vultr' vultr.txt && egrep 'vultr' vultr.txt
Output:

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.