Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use regular expression in if-condition in bash

Tags:

regex

bash

I wonder the general rule to use regular expression in if clause in bash?

Here is an example

$ gg=svm-grid-ch   $ if [[ $gg == *grid* ]] ; then echo $gg; fi   svm-grid-ch   $ if [[ $gg == ^....grid* ]] ; then echo $gg; fi   $ if [[ $gg == ....grid* ]] ; then echo $gg; fi   $ if [[ $gg == s...grid* ]] ; then echo $gg; fi   $    

Why the last three fails to match?

Hope you could give as many general rules as possible, not just for this example.

like image 953
Tim Avatar asked Feb 27 '10 18:02

Tim


People also ask

Can we use if condition in regular expression?

If-Then-Else Conditionals in Regular Expressions. A special construct (? ifthen|else) allows you to create conditional regular expressions. If the if part evaluates to true, then the regex engine will attempt to match the then part.

Can you use regex in bash?

Regex is a very powerful tool that is available at our disposal & the best thing about using regex is that they can be used in almost every computer language. So if you are Bash Scripting or creating a Python program, we can use regex or we can also write a single line search query.

How do you check if a string matches a regex in bash?

You can use the test construct, [[ ]] , along with the regular expression match operator, =~ , to check if a string matches a regex pattern (documentation). where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.

What is bash if [- N?

A null string in Bash can be declared by equalizing a variable to “”. Then we have an “if” statement followed by the “-n” flag, which returns true if a string is not null. We have used this flag to test our string “name,” which is null.


2 Answers

When using a glob pattern, a question mark represents a single character and an asterisk represents a sequence of zero or more characters:

if [[ $gg == ????grid* ]] ; then echo $gg; fi 

When using a regular expression, a dot represents a single character and an asterisk represents zero or more of the preceding character. So ".*" represents zero or more of any character, "a*" represents zero or more "a", "[0-9]*" represents zero or more digits. Another useful one (among many) is the plus sign which represents one or more of the preceding character. So "[a-z]+" represents one or more lowercase alpha character (in the C locale - and some others).

if [[ $gg =~ ^....grid.*$ ]] ; then echo $gg; fi 
like image 67
Dennis Williamson Avatar answered Oct 16 '22 08:10

Dennis Williamson


Use =~

for regular expression check Regular Expressions Tutorial Table of Contents

like image 36
Enrico Carlesso Avatar answered Oct 16 '22 08:10

Enrico Carlesso