Linux Shell 脚本 - 字符串与通配符的比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19891491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linux Shell Script - String Comparison with wildcards
提问by AlexT82
I am trying to see if a string is part of another string in shell script (#!bin/sh).
我正在尝试查看一个字符串是否是 shell 脚本 (#!bin/sh) 中另一个字符串的一部分。
The code i have now is:
我现在的代码是:
#!/bin/sh
#Test scriptje to test string comparison!
testFoo () {
t1=
t2=
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".
我正在寻找的结果是,我想知道“bla1”中何时存在“bla”。
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?
更新:我已经尝试了这里描述的“包含”函数:如何判断一个字符串是否包含 Unix shell 脚本中的另一个字符串?
As well as the syntax in String contains in bash
以及字符串中的语法包含在 bash 中
However, they seem to be non compatible with normal shell script (bin/sh)...
但是,它们似乎与普通的 shell 脚本 (bin/sh) 不兼容...
Help?
帮助?
采纳答案by glenn Hymanman
In bash you can write (note the asterisks are outsidethe quotes)
在 bash 中你可以写(注意星号在引号之外)
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
对于 /bin/sh,=
运算符仅用于相等而不用于模式匹配。您可以使用case
,虽然
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.
如果您专门针对 linux,我会假设 /bin/bash 的存在。