我正在尝试查看一个字符串是否是 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) 不兼容...
帮忙吗?
最佳答案
在 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。
关于Linux Shell 脚本 - 带通配符的字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19891491/