Case insensitive comparison of strings in shell sc

2020-01-25 15:54发布

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

12条回答
可以哭但决不认输i
2楼-- · 2020-01-25 16:36

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^^}
查看更多
仙女界的扛把子
3楼-- · 2020-01-25 16:36

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
查看更多
仙女界的扛把子
4楼-- · 2020-01-25 16:43

Here is my solution using tr:

var1=match
var2=MATCH
var1=`echo $var1 | tr '[A-Z]' '[a-z]'`
var2=`echo $var2 | tr '[A-Z]' '[a-z]'`
if [ "$var1" = "$var2" ] ; then
  echo "MATCH"
fi
查看更多
beautiful°
5楼-- · 2020-01-25 16:45

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
查看更多
做个烂人
6楼-- · 2020-01-25 16:48

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"
  }
}'
查看更多
一纸荒年 Trace。
7楼-- · 2020-01-25 16:48

grep has a -i flag which means case insensitive 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
查看更多
登录 后发表回答