Linux Shell脚本-使用通配符进行字符串比较
我正在尝试查看一个字符串是否是shell脚本(#!bin/sh)中另一个字符串的一部分 我现在的代码是:Linux Shell脚本-使用通配符进行字符串比较,linux,string,shell,sh,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 ar
#!/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”
谢谢和亲切的问候
更新:
我已经尝试了以下两种“包含”函数:
以及中的语法
但是,它们似乎与普通shell脚本(bin/sh)不兼容
帮助?您可以在bash中编写(注意星号在引号之外)
对于/bin/sh,=
运算符仅用于相等,不用于模式匹配。您可以使用案例
case "$t1" in
*"$t2"*) echo t1 contains t2 ;;
*) echo t1 does not contain t2 ;;
esac
如果您是专门针对linux的,我会假设存在/bin/bash 检查同样的问题并在这里回答:谢谢你,格伦!非常感谢!(这是一个linux环境,但是非常轻量级,没有/bin/bash,所以我真的需要/bin/sh版本!-再次感谢!)比处理case更好,使用=~operator:if[$t1=~%t2*];回声匹配;fi@lef,对于正则表达式,您需要
[[$t1=~“$t2”]
@glenn,对了,除了输入错误(%t2而不是$t2),sh实际上可能不支持双括号[[]]Omg这太违反直觉了!谢谢,这很有道理。
case "$t1" in
*"$t2"*) echo t1 contains t2 ;;
*) echo t1 does not contain t2 ;;
esac