Case insensitive string comparison in shell script

The == operator is used to compare two lines in a shell script. However, I want to compare two lines, ignoring the case, how can this be done? Is there a standard command for this?

+103
string shell case-insensitive compare
Nov 13 '09 at 11:31
source share
11 answers

if you have bash

 str1="MATCH" str2="match" shopt -s nocasematch case "$str1" in $str2 ) echo "match";; *) echo "no match";; esac 

Otherwise, you must tell us which shell you are using.

using awk

 str1="MATCH" str2="match" awk -vs1="$str1" -vs2="$str2" 'BEGIN { if ( tolower(s1) == tolower(s2) ){ print "match" } }' 
+57
Nov 13 '09 at 12:02
source share

In Bash, you can use the parameter extension to change the string to all lower / upper case:

 var1=TesT var2=tEst echo ${var1,,} ${var2,,} echo ${var1^^} ${var2^^} 
+126
Oct. 16 '13 at 7:20
source share

All of these answers ignore the easiest and fastest way to do this (if you have Bash 4):

 if [ "${var1,,}" = "${var2,,}" ]; then echo ":)" fi 

All you do is convert both strings to lowercase and compare the results.

+91
Dec 28 '14 at 19:13
source share

Same as ghostdog74's answer, but slightly different code

 shopt -s nocasematch [[ "foo" == "Foo" ]] && echo "match" || echo "notmatch" shopt -u nocasematch 
+28
Jan 03 '13 at 11:45
source share

One way would be to convert both strings to the top or bottom:

 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 
+11
Nov 13 '09 at 11:52
source share

For the korn shell, I use the built-in set command (-l for lowercase and -u for uppercase).

 var=True typeset -l var if [[ $var == "true" ]]; then print "match" fi 
+7
Sep 26 '13 at 22:17
source share

Very easy if you do frrep for case insensitive comparison:

 str1="MATCH" str2="match" if [[ $(fgrep -ix $str1 <<< $str2) ]]; then echo "case-insensitive match"; fi 
+5
May 31 '16 at 18:46
source share

grep has the -i flag which means that the register is not -i so ask it to tell you if var2 is in var1.

 var1=match var2=MATCH if echo $var1 | grep -i "^${var2}$" > /dev/null ; then echo "MATCH" fi 
+2
Apr 27 '10 at 20:00
source share

Here is my solution using tr:

 var1=match var2=MATCH var1=`echo $var1 | tr '[AZ]' '[az]'` var2=`echo $var2 | tr '[AZ]' '[az]'` if [ "$var1" = "$var2" ] ; then echo "MATCH" fi 
+2
May 09 '16 at 19:01
source share

shopt -s nocaseglob

+1
Nov 13 '09 at 11:38
source share

For zsh syntax is slightly different:

 > str1='MATCH' > str2='match' > [ "$str1" == "$str2:u" ] && echo 'Match!' Match! > 

This will convert str2 to uppercase before comparing.

Additional examples for change below:

 > xx=Test > echo $xx:u TEST > echo $xx:l test 
+1
Jul 18 '18 at 0:31
source share



All Articles