简体   繁体   中英

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>

just use

shopt -s nocasematch

before your command.

alternatively

shopt -s nocasematch && [[ 'doG' =~ (cat)|(dog) ]] && echo 'hi' || echo 'no match'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM