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条回答
Luminary・发光体
2楼-- · 2020-01-25 16:29

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.

查看更多
Rolldiameter
3楼-- · 2020-01-25 16:30

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
查看更多
We Are One
4楼-- · 2020-01-25 16:31

Same as answer from ghostdog74 but slightly different code

shopt -s nocasematch
[[ "foo" == "Foo" ]] && echo "match" || echo "notmatch"
shopt -u nocasematch
查看更多
看我几分像从前
5楼-- · 2020-01-25 16:31

I came across this great blog/tutorial/whatever about dealing with case sensitive pattern. The following three methods are explained in details with examples:

1. Convert pattern to lowercase using tr command

opt=$( tr '[:upper:]' '[:lower:]' <<<"$1" )
case $opt in
        sql)
                echo "Running mysql backup using mysqldump tool..."
                ;;
        sync)
                echo "Running backup using rsync tool..."
                ;;
        tar)
                echo "Running tape backup using tar tool..."
                ;;
        *)
                echo "Other options"
                ;;
esac

2. Use regex with case patterns

opt=$1
case $opt in
        [Ss][Qq][Ll])
                echo "Running mysql backup using mysqldump tool..."
                ;;
        [Ss][Yy][Nn][Cc])
                echo "Running backup using rsync tool..."
                ;;
        [Tt][Aa][Rr])
                echo "Running tape backup using tar tool..."
                ;;
        *)
                echo "Other option"
                ;;
esac

3. Turn on nocasematch

opt=$1
shopt -s nocasematch
case $opt in
        sql)
                echo "Running mysql backup using mysqldump tool..."
                ;;
        sync)
                echo "Running backup using rsync tool..."
                ;;
        tar)
                echo "Running tape backup using tar tool..."
                ;;
        *)
                echo "Other option"
                ;;
esac

shopt -u nocasematch
查看更多
萌系小妹纸
6楼-- · 2020-01-25 16:32

For zsh the syntax is slightly different:

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

This will convert str2 to uppercase before the comparison.

More examples for changing case below:

> xx=Test
> echo $xx:u
TEST
> echo $xx:l
test
查看更多
Bombasti
7楼-- · 2020-01-25 16:35

shopt -s nocaseglob

查看更多
登录 后发表回答