The equalsIgnoreCase() method of the String class is similar to the equals() method the difference if this method compares the given string to the current one ignoring case.
Yes, it is case sensitive, just like the rest of UNIX.
When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.
Here are all the ways in which variables are substituted in Shell: ${variable} This command substitutes the value of the variable. ${variable:-word} If a variable is null or if it is not set, word is substituted for variable.
In Bash, you can use parameter expansion to modify a string to all lower-/upper-case:
var1=TesT
var2=tEst
echo ${var1,,} ${var2,,}
echo ${var1^^} ${var2^^}
All of these answers ignore the easiest and quickest way to do this (as long as you have Bash 4):
if [ "${var1,,}" = "${var2,,}" ]; then
echo ":)"
fi
All you're doing there is converting both strings to lowercase and comparing the results.
if you have bash
str1="MATCH"
str2="match"
shopt -s nocasematch
case "$str1" in
$str2 ) echo "match";;
*) echo "no match";;
esac
otherwise, you should tell us what shell you are using.
alternative, using awk
str1="MATCH"
str2="match"
awk -vs1="$str1" -vs2="$str2" 'BEGIN {
if ( tolower(s1) == tolower(s2) ){
print "match"
}
}'
Save the state of nocasematch
(in case some other function is depending on it being disabled):
local orig_nocasematch=$(shopt -p nocasematch; true)
shopt -s nocasematch
[[ "foo" == "Foo" ]] && echo "match" || echo "notmatch"
$orig_nocasematch
Note that
local
is only required inside a function.
Also, the; true
part will prevent the shell from exiting whenset -e
is on and$(shopt -p nocasematch)
fails (because nocasematch was NOT set at all).
One way would be to convert both strings to upper or lower:
test $(echo "string" | /bin/tr '[:upper:]' '[:lower:]') = $(echo "String" | /bin/tr '[:upper:]' '[:lower:]') && echo same || echo different
Another way would be to use grep:
echo "string" | grep -qi '^String$' && echo same || echo different
For korn shell, I use typeset built-in command (-l for lower-case and -u for upper-case).
var=True
typeset -l var
if [[ $var == "true" ]]; then
print "match"
fi
Very easy if you fgrep to do a case-insensitive line compare:
str1="MATCH"
str2="match"
if [[ $(fgrep -ix $str1 <<< $str2) ]]; then
echo "case-insensitive match";
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With