Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use regular expressions in bash scripts?

I want to check if a variable has a valid year using a regular expression. Reading the bash manual I understand I could use the operator =~

Looking at the example below, I would expect to see "not OK" but I see "OK". What am I doing wrong?

i="test" if [ $i=~"200[78]" ] then   echo "OK" else   echo "not OK" fi 
like image 988
idrosid Avatar asked Nov 20 '08 10:11

idrosid


People also ask

Can you use regular expressions in bash?

Using the power of regular expressions, one can parse and transform textual based documents and strings. This article is for advanced users, who are already familiar with basic regular expressions in Bash.

What is regular expression in bash?

A regular expression is some sequence of characters that represents a pattern. For example, the [0-9] in the example above will match any single digit where [A-Z] would match any capital letter. [A-Z]+ would match any sequence of capital letters.

What is regex in shell script?

A regular expression (regex) is a text pattern that can be used for searching and replacing. Regular expressions are similar to Unix wild cards used in globbing, but much more powerful, and can be used to search, replace and validate text.


2 Answers

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test" if [[ $i =~ 200[78] ]] ; then     echo "OK" else     echo "not OK" fi 
like image 151
paxdiablo Avatar answered Sep 19 '22 05:09

paxdiablo


You need spaces around the operator =~

 i="test" if [[ $i =~ "200[78]" ]]; then   echo "OK" else   echo "not OK" fi 
like image 34
michiel Avatar answered Sep 21 '22 05:09

michiel