Regular expressions with bash =~

A number of articles in the web give examples of how to use the bash regular expression operator =~ that exists since bash version 3. However the majority of these examples did not work for me.

The enlightenment occured when I had fully digested the sentence Any part of the pattern may be quoted to force it to be matched as a string. That means this example (taken from http://aplawrence.com/Linux/bash-regex.html) does not work:

 

 

if [[ "$input" =~ 'foo(.*)' ]]
then
        echo $BASH_REMATCH is what I wanted   
        echo but just ${BASH_REMATCH[1]}
fi

The reason is that the regular expression is quoted with single quotes and thus matched as a string. A regular expression like …

([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([a-z/0-9]+)

… will actually trigger an error, since the shell will try to interpret the breakets as shell grammar. One solution I found to this mess is to assign the regular expression to a variable and then match against this variable:

regex='([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([a-z/0-9]+)'
if [[ "${params}" =~ $regex ]]
then
case "${BASH_REMATCH[5]}" in

There’s probably a simpler way, but this one at least works. 😉

Leave a Reply

Your email address will not be published. Required fields are marked *