Wednesday, June 16, 2010

Case insensitive regex in bash

By default regexes in [[ ]] are case sensitive. If you want to match in a case insensitive way you have to set the shell option nocasematch.


mytext="eXistenZ"
if [[ $mytext =~ existenz ]];
then
echo "yep"
else
echo "nope"
fi

If you run the above script you should get "nope" as the output. For case insensitive matching just insert this into the script prior to the regex:

shopt -s nocasematch;


You can unset the nocasematch shell option using the following: shopt -u nocasematch

Here's a more complete example:

mytext="eXistenZ"
function testText
{
if [[ $mytext =~ existenz ]];
then
echo "yep"
else
echo "nope"
fi;
}
testText
shopt -s nocasematch
testText


If you run that script then the output is:

nope
yep

2 comments:

  1. Thanks a lot!!

    This really helped me!

    ReplyDelete
  2. Great explanation, thank you!

    ReplyDelete