Jonathan Matthews Jonathan Matthews - 1 year ago 70
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 Source

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 [[ ... ]]).

[[ "$string" =~ $regex ]] && echo "matches"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download