Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to construct regex to compare case insensitive strings in shell script?

I am passing command line arguments to a shell script and it is being compared aganist a regular expression. The following code is case-sensitive:

[[ $1 =~ ^(cat)|(dog)$ ]] && echo "match" || echo "no match"

How can I modify this regex that will ignore cases? I would be able to pass cAt and it should match.

I want to use /i regex flag as it ignores cases. But how do I use it inside a shell script? I have tried [[ $1 =~ /(cat)|(dog)/i ]] but the script exited with a syntax error.

StackOverflow has a similar question but it does not answer my inquiry. I want to use test to compare both strings and not interested to use shopt -s nocasematch or grep <expression>

like image 919
Sedmaister Avatar asked Dec 17 '25 18:12

Sedmaister


1 Answers

just use

shopt -s nocasematch

before your command.

alternatively

shopt -s nocasematch && [[ 'doG' =~ (cat)|(dog) ]] && echo 'hi' || echo 'no match'
like image 178
Derviş Kayımbaşıoğlu Avatar answered Dec 19 '25 13:12

Derviş Kayımbaşıoğlu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!