Jonathan Matthews Jonathan Matthews - 21 days ago 9
Bash Question

Match a single character in a Bash regular expression

For some reason, the following regular expression match doesn't seem to be working.

string="#Hello world";
[[ "$string" =~ 'ello' ]] && echo "matches";
[[ "$string" =~ 'el.o' ]] && echo "matches";


The first command succeeds (as expected), but the second one does not.

Shouldn't that period be treated by the regular expression as a single character?

Answer

Quoting the period causes it to be treated as a literal character, not a regular-expression metacharacter. Best practice if you want to quote the entire regular expression is to do so in a variable, where regular expression matching rules aren't in effect, then expand the parameter unquoted (which is safe to do inside [[ ... ]]).

regex='el.o'
[[ "$string" =~ $regex ]] && echo "matches"
Comments