String Comparison with wildcards

I am trying to see if a string is part of another string in shell script (#!bin/sh).

The code i have now is:

#!/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"

The result I'm looking for, is that I want to know when "bla" exists in "bla1".

Thanks and kind regards,

UPDATE: I've tried both the "contains" function as described here: How do you tell if a string contains another string in Unix shell scripting?

As well as the syntax in String contains in bash

However, they seem to be non compatible with normal shell script (bin/sh)...

Help?


In bash you can write (note the asterisks are outside the quotes)

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

For /bin/sh, the = operator is only for equality not for pattern matching. You can use case though

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

If you're specifically targetting linux, I would assume the presence of /bin/bash.

链接地址: http://www.djcxy.com/p/36204.html

上一篇: 在shell脚本中比较两个字符串变量

下一篇: 字符串与通配符比较