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
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.
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.
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.
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
You need spaces around the operator =~
i="test" if [[ $i =~ "200[78]" ]]; then echo "OK" else echo "not OK" fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With