linux字符串怎么比较大小写,shell脚本中字符串的不区分大小写比较

shell脚本中字符串的不区分大小写比较

==运算符用于比较shell脚本中的两个字符串。 但是,我想比较两个忽略大小写的字符串,怎么做呢? 这有什么标准命令吗?

11个解决方案

126 votes

在Bash中,您可以使用参数扩展将字符串修改为所有低/大写:

var1=TesT

var2=tEst

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

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

alphaniner answered 2019-07-24T11:43:27Z

88 votes

所有这些答案都忽略了最简单快捷的方法(只要你有Bash 4):

if [ "${var1,,}" = "${var2,,}" ]; then

echo ":)"

fi

你所做的就是将两个字符串转换为小写并比较结果。

Riot answered 2019-07-24T11:43:59Z

52 votes

如果你有bash

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"

}

}'

ghostdog74 answered 2019-07-24T11:43:03Z

26 votes

与ghostdog74的回答相同但代码略有不同

shopt -s nocasematch

[[ "foo" == "Foo" ]] && echo "match" || echo "notmatch"

shopt -u nocasematch

Gerry Hickman answered 2019-07-24T11:44:24Z

11 votes

一种方法是将两个字符串转换为上限或下限:

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

Randy Proctor answered 2019-07-24T11:44:56Z

7 votes

对于korn shell,我使用了排版内置命令(-l表示小写,-u表示大写)。

var=True

typeset -l var

if [[ $var == "true" ]]; then

print "match"

fi

Ek C. answered 2019-07-24T11:45:20Z

4 votes

如果你fgrep做一个不区分大小写的行比较很容易:

str1="MATCH"

str2="match"

if [[ $(fgrep -ix $str1 <<< $str2) ]]; then

echo "case-insensitive match";

fi

Cooper F. Nelson answered 2019-07-24T11:45:44Z

2 votes

var1=match

var2=MATCH

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

echo "MATCH"

fi

Larry answered 2019-07-24T11:46:02Z

2 votes

这是我使用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

stones333 answered 2019-07-24T11:46:26Z

1 votes

shopt -s nocaseglob

ennuikiller answered 2019-07-24T11:46:50Z

1 votes

对于str2,语法略有不同:

> str1='MATCH'

> str2='match'

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

Match!

>

这将在比较之前将str2转换为大写。

更改以下案例的更多示例:

> xx=Test

> echo $xx:u

TEST

> echo $xx:l

test

smac89 answered 2019-07-24T11:47:28Z

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值