How To Use Regular Expression – Regex In Bash Linux?

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

Linux bash provides a lot of commands and features for Regular Expressions or regex. grep , expr , sed and awk  are some of them. Bash also have =~ operator which is named as RE-match  operator. In this tutorial we will look =~  operator and use cases. More information about regex command cna be found in the following tutorials.

Introduction to Linux Grep Command With Examples

Awk Regular Expression Commands and Examples

Ultimate Sed Tutorial With Examples

Syntax

Syntax of the bash rematch is very easy we just provide the string and then put the operator and the last one is the regular expression we want to match. We also surround the expression with double brackets like below.

Match Digits

In daily bash shell usage we may need to match digits or numbers. We can use bash regex operator. We will state numbers with [0-9] like below. But keep in mind that bash regex can be fairly complicated in some cases. In this example we will simple match given line for digits

Match Digits
Match Digits

Specify Start Of Line

In previous example we have matched digits in the whole line. This is not case some times. We may need to match from start of the line with digits of other character type. We can use ^ to specify start of the line. In this example we will match line which starts with 123 . As we can see it didn’t match.

LEARN MORE  How To Pass and Parse Linux Bash Script Arguments and Parameters

Specify Start Of Line
Specify Start Of Line

Specify End Of Line

We can also specify the end on line. We will use $  to specify end of line. We will match line which ends with any digit.

Match Email

Digit patterns are easy to express but how can we express email regex in bash. We can use following regex pattern for emails generally.

We will ommit suffixes like com , net  , gov  etc. because there is a lot of possibilities. As we know @ is sitting between username and domain name.

Match Email
Match Email

Match IP Address

IP address is another type of important data type which is used in bash and scripting. We can match IP addresses by using bash regex. We will use following regex pattern which is the same with tools like grep  and others.

LEARN MORE  Linux Command Not Found Error And Solution

 

Match IP Address
Match IP Address

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