grep
is a very popular tool used to match given search patterns in the given text. grep provides a simple glob search but also provides regex support which is very useful for complex search ant matches. In this tutorial, we will examine how to use for regex patterns.
Enable Regex with Grep
By default grep
do not supports regex
patterns. We can enable regex
for grep
with -E
option like below. -E
option means extended grep with advanced features like regex
.
$ grep -E 'ismail' /etc/passwd
OR we can use alias named egrep
which is the same as grep -E
like below.
$ egrep 'ismail' /etc/passwd
Match Start Of Line
We can match the start of the line with the ^
sign by using it at the start of the search pattern. In this example, we will list lines which start with d
.
$ egrep '^d' /etc/passwd

Match End Of Line
We can also match end of the line with the $
sign. We will put $
to the end of line and provide the last character we want to match. In this example we will try to match nologin
at the end of line.
$ egrep 'nologin$'

Lines Containing Given Text
We can also use it to match the given pattern without any special usage. We will match the term mail
with the grep.
$ egrep 'mail' /etc/passwd
Match Uppercase Letters
We can match uppercase letters with [AZ]
or [[:upper:]]
like below.
$ egrep '[[:upper:]]' /etc/passwd

Match Lowercase Letters
We can match uppercase letters with [az]
or [[:lower:]]
like below.
$ egrep '[[:lower:]]' /etc/passwd

Match By Ignoring Case
We have match upper and lowercase letters in previous examples but what if we need to match by ignoring case with lowercase or uppercase for the given term. We will provide -i
option like below.
$ egrep -i 'r' /etc/passwd

Match Any Single Character
If we want to match any single character we can use .
which means just a character. In this example, we will match r..t
.
$ egrep 'r..t' /etc/passwd
Logical OR Multiple Patterns
We can or multiple patterns with |
. In this example we will match root
or ismail
.
$ egrep 'root|ismail' /etc/passwd
Match Blank Line
We can match blank line which contains no character even a space by using ^
and $
like below.
$ egrep '^
Match Digits
We can match lines which contains numbers or digits with [09]
or [[:digit:]]
like below.
$ egrep '[[:digit:]]' /etc/passwd

/etc/passwd
