Linux Shell脚本 - 与通配符的字符串比较

时间:2013-11-10 15:26:53

标签: linux string shell sh

我正在尝试查看字符串是否是shell脚本中另一个字符串的一部分(#!bin / sh)。

我现在的代码是:

#!/bin/sh
#Test scriptje to test string comparison!

testFoo () {
        t1=$1
        t2=$2
        echo "t1: $t1 t2: $t2"
        if [ $t1 == "*$t2*" ]; then
                echo "$t1 and $t2 are equal"
        fi
}

testFoo "bla1" "bla"

我正在寻找的结果是,我想知道“bla1”中存在“bla”的时间。

谢谢和亲切的问候,

更新: 我已尝试过两种“包含”功能,如下所述:How do you tell if a string contains another string in Unix shell scripting?

以及String contains in bash

中的语法

但是,它们似乎与普通的shell脚本(bin / sh)不兼容......

帮助?

1 个答案:

答案 0 :(得分:43)

在bash中你可以写(注意星号在引号)

    if [[ $t1 == *"$t2"* ]]; then
            echo "$t1 and $t2 are equal"
    fi

对于/ bin / sh,=运算符仅用于等式而不用于模式匹配。您可以使用case

case "$t1" in
    *"$t2"*) echo t1 contains t2 ;;
    *) echo t1 does not contain t2 ;;
esac

如果你专门针对linux,我会假设存在/ bin / bash。

相关问题