3

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>

2 Answers 2

3

just use

shopt -s nocasematch

before your command.

alternatively

shopt -s nocasematch && [[ 'doG' =~ (cat)|(dog) ]] && echo 'hi' || echo 'no match'
Sign up to request clarification or add additional context in comments.

1 Comment

Asker said that he does not want to use shopt -s nocasematch :/
0

While the accepted answer's shopt -s nocasematch is fine for many cases, I very much prefer to keep shopt -u nocasematch to be more explicit about matches.

This uses bash's variable expansion and asks bash to convert the expanded output to lowercase [documentation] to achieve your desired result, while also allowing other code to be case sensitive when needed:

shopt -u nocasematch # turn regex case-sensitivity on
test() { [[ "${1,,}" =~ ^(cat)|(dog)$ ]] && echo "match" || echo "no match"; }
test cat
test cAt
test ""

->

match
match
no match

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.