Programing

쉘 스크립트에서 대소 문자를 구분하지 않는 문자열 비교

lottogame 2020. 7. 22. 21:29
반응형

쉘 스크립트에서 대소 문자를 구분하지 않는 문자열 비교


==연산자는 쉘 스크립트에서 두 문자열을 비교하는 데 사용됩니다. 그러나 대소 문자를 무시하고 두 문자열을 비교하고 싶습니다. 어떻게 수행 할 수 있습니까? 이에 대한 표준 명령이 있습니까?


배쉬가 있다면

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

그렇지 않으면 사용중인 쉘을 알려주십시오.

대안, awk 사용

str1="MATCH"
str2="match"
awk -vs1="$str1" -vs2="$str2" 'BEGIN {
  if ( tolower(s1) == tolower(s2) ){
    print "match"
  }
}'

Bash에서는 매개 변수 확장을 사용하여 문자열을 모두 소문자 / 대문자로 수정할 수 있습니다.

var1=TesT
var2=tEst

echo ${var1,,} ${var2,,}
echo ${var1^^} ${var2^^}

이 모든 대답은 Bash 4가있는 한 가장 쉽고 빠른 방법을 무시합니다.

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

당신이하고있는 일은 두 문자열을 모두 소문자로 변환하고 결과를 비교하는 것입니다.


ghostdog74의 답변과 동일하지만 약간 다른 코드

shopt -s nocasematch
[[ "foo" == "Foo" ]] && echo "match" || echo "notmatch"
shopt -u nocasematch

한 가지 방법은 두 문자열을 모두 위 또는 아래로 변환하는 것입니다.

test $(echo "string" | /bin/tr '[:upper:]' '[:lower:]') = $(echo "String" | /bin/tr '[:upper:]' '[:lower:]') && echo same || echo different

다른 방법은 grep을 사용하는 것입니다.

echo "string" | grep -qi '^String$' && echo same || echo different

korn 쉘의 경우 typeset 내장 명령을 사용합니다 (소문자는 -l, 대문자는 -u).

var=True
typeset -l var
if [[ $var == "true" ]]; then
    print "match"
fi

대소 문자를 구분하지 않는 라인 비교를 fgrep하면 매우 쉽습니다.

str1="MATCH"
str2="match"

if [[ $(fgrep -ix $str1 <<< $str2) ]]; then
    echo "case-insensitive match";
fi

다음은 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

grep-i대소 문자를 구분을 의미하므로 VAR2가 var1에있는 경우 당신에게 그것을 요구 플래그.

var1=match 
var2=MATCH 
if echo $var1 | grep -i "^${var2}$" > /dev/null ; then
    echo "MATCH"
fi

shopt -s nocaseglob


대한 zsh구문과 약간 다릅니다 :

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

str2비교하기 전에 대문자 로 변환 됩니다.

아래 사례를 변경하기위한 추가 예 :

> xx=Test
> echo $xx:u
TEST
> echo $xx:l
test

참고 URL : https://stackoverflow.com/questions/1728683/case-insensitive-comparison-of-strings-in-shell-script

반응형