How to Use the egrep Command in Linux
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 lettera
in 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 samegrep
character without escaping inegrep
to 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.txt
files 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
dir
directory and thesub_dir
subdirectory underdir1
. The-p
option creates the parent directory if it does not exist.Create a new sample
vultr.txt
file 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
Vultr
keyword in thevultr.txt
file.console$ egrep 'Vultr' vultr.txt
Output:
Highlight the color of the
Vultr
keyword using the--color
option.console$ egrep --color=auto 'Vultr' vultr.txt
Output:
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 invultr.txt
and displays all results that match any case, ignoring case sensitivity. For example,vultr
,Vultr
, andVULTR
match the search.Output:
Run an inverted search to find the lines that do not contain the
vultr
keyword .console$ egrep -v 'vultr' vultr.txt
Output:
Count the matching lines containing the
Vultr
keyword.console$ egrep -c 'Vultr' vultr.txt
Output:
Display lines that contain the
Vultr
keyword along with the respective line numbers.console$ egrep -n 'Vultr' vultr.txt
Output:
Search multiple files to find lines that contain the
Vultr
keyword.console$ egrep 'Vultr' vultr.txt Vultr.txt
Output:
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:
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 invultr.txt
along with the line numbers.Output:
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 thevultr.txt
file along with the line numbers.Output:
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 invultr.txt
file.Output:
Use Advanced egrep
Command Options
Follow the steps below to use the advanced egrep
command options.
Search for lines containing
Example
followed by thefrom
keywords using group search.console$ egrep '(Example.*from)' vultr.txt
The above command searches for lines in
vultr.txt
where any characters follow theExample
keyword and then thefrom
keyword .Output:
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 containvultr
as 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.txt
that match theVultr
keyword 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.txt
file.console$ nano sample.txt
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.
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:
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:
Character Classes: Match any character in brackets
[ ]
.Search for any line that contains lowercase letters between
a
andf
.console$ egrep '[a-f]' sample.txt
The above pattern matches any lowercase letter from
a
tof
to 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
0
to9
and 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
a
keyword.console$ egrep 'a*' sample.txt
Output:
Search for lines with one or more occurrences of the
a
keyword.console$ egrep 'a+' sample.txt
Output:
Search for lines that contain the
logs
keyword followed by an optionals
(to match bothlog
andlogs
) in thesample.txt
file.console$ egrep 'logs?' sample.txt
The above pattern matches all lines that contain
log
orlogs
. The (?
) question mark symbol makes thes
character optional.Output:
Alternation: Match either pattern using the
|
pipe symbol.Search for lines that contain either
error
orwarning
.console$ egrep 'error|warning' sample.txt
The above pattern matches all lines that contain either the
error
orwarning
keywords.Output:
Grouping: Match group patterns using parenthesis
( )
.Search for lines that contain either the
error
orwarning
followed by thelog
keywords.console$ egrep '(error|warning) log' sample.txt
Output:
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 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
error
keyword without any additional text.console$ egrep '^error$' sample.txt
Output:
Combine egrep
with Other Commands
Use
egrep
withpipe
to filter the output of another command as theegrep
input. For example, run the following command to find lines that contain thedata
keyword in theps aux
command output.console$ ps aux | egrep 'data'
Output:
Combine
egrep
withfind
to search for patterns in files listed byfind
. For example, run the following command to search for theHello
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 theHello
keyword in the files.Output:
Combine
egrep
withxargs
for a more efficient search. For example, search for theHello
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 toegrep
to search for theHello
keyword.xargs
improves efficiency by passing multiple files toegrep
in a single command.Output:
Combine
egrep
withwc
command.console$ egrep -o 'Vultr' vultr.txt | wc -l
The above command counts the number of times the
Vultr
keyword appears in thevultr.txt
file. The-o
option instructsegrep
to print only the matching parts whilewc -l
counts the number of lines in the search results.Output:
Use Additional egrep
Command in Linux with Examples
Search for lines that contain either the
Greetings
or theVultr
keywords from thevultr.txt
file 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
vultr
keyword 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.