首页 > Bash Shell怎么判断字符串的包含关系

Bash Shell怎么判断字符串的包含关系

在Bash Shell里处理字符串,怎么能判断一个字符串是不是另一个的子字符串?
有木有灰常简单的方法啊~~~


最简单的是用expr命令:

sorry, index貌似不是我想的那个意思,expr index strings chars,只要chars中的任意一个字符在strings中出现,就返回所在的位置,否则返回0

$ str="hello,world"
$ expr match "$str" ".*llo"
5
$ expr match "$str" ".*llt"
0

所以如何判断一个字符串是否包含某个子串:

$ test `expr match "$str" ".*$pat"` -ne 0

当然也是可以用grep命令来判断的:

$ echo “$str” | grep -q ”$pat”
$ echo $?

简单示例:

#!/bin/sh

thisString="1 2 3 4 5" # 源字符串
searchString="1 2" # 搜索字符串

case $thisString in 
    *"$searchString"*) echo Enemy Spot ;;
    *) echo nope ;;
esac

可以换个角度,这样考虑,试图替换原字符串中的模式串内容:

function substr
{
    STRING_A=$1
    STRING_B=$2

    if [[ ${STRING_A/${STRING_B}//} == $STRING_A ]]
    then
        ## is not substring.
        echo N
        return 0
    else
        ## is substring.
        echo Y
        return 1
    fi
}

substr "ThisIsAString" "SUBString" # should output N
substr "ThisIsAString" "String" # should output Y

#!/bin/bash

strA="dkasnfk"
strB="asn"
strC="knk"

result=$(echo $strA | grep "${strC}")
if [[ "$result" != "" ]]
then
    echo "True"
else
    echo "False"
fi

string='My string';

if [[ $string == *My* ]]
then
echo "It's there!";
fi

http://stackoverflow.com/questions/229551/string-contains-in-bash

【热门文章】
【热门文章】