How To Use Regex (Regular Expression) with Grep?

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/how-to-use-regex-regular-expression-with-grep/
PINTEREST
PINTEREST
INSTAGRAM

grep is very popular tool used to match given search patterns in given text. grep provides simple glob search but also provides regexsupport which is very useful for complex search ant matches. In this tutorial we will examine how to use grep for regex patterns.

Enable Regex with Grep

By default grep do not supports regex patterns. We can enable regexfor grep with -E option like below. -E option means extended grep with advanced features like regex.

Enable Regex with Grep
Enable Regex with Grep

OR we can use alias named egrep which is the same as grep -E like below.

Match Start Of Line

We can match start of the line with the ^ sign by using it in the start of the search pattern. In this example we will list lines which starts with  d .

Start Of Line
Start Of Line

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.

End Of Line
End Of Line

Lines Containing Given Text

We can also use to match given pattern without any special usage. We will match the term mail with the grep.

Lines Containing Given Text
Lines Containing Given Text

Match Uppercase

We can match uppercase letters with [AZ] or [[:upper:]] like below.

LEARN MORE  How To Grep Text Files With Powershell Grep or Select-String Cmdlet In Windows?

Match Uppercase 
Match Uppercase 

Match Lowercase

We can match uppercase letters with [az] or [[:lower:]] like below.

Match Lowercase
Match Lowercase

Match 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 given term. We will provide -i option like below.

Match Ignoring Case
Match Ignoring Case

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 .

Match Any Single Character
Match Any Single Character

Logical OR Multiple Patterns

We can or multiple patterns with | . In this example we will match root or ismail .

Logical OR
Logical OR

Match Blank Line

We can match blank line which contains no character even a space by using ^ and $ like below.

Match Digits

We can match lines which contains numbers or digits with [09] or [[:digit:]] like below.

Match Digits
Match Digits

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/how-to-use-regex-regular-expression-with-grep/
PINTEREST
PINTEREST
INSTAGRAM