我在Bash中有一个字符串:
string="My string"
如何测试它是否包含另一个字符串?
if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
其中??
是我的未知操作符。我要使用echo
和grep
吗
if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
这看起来有点笨拙。
发布于 2008-10-23 12:55:25
如果使用双括号,也可以在case语句之外使用Marcus's answer (* wildcards):
string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi
请注意,针形字符串中的空格需要放在双引号之间,*
通配符应该放在外部。还要注意,使用的是简单的比较运算符(即==
),而不是正则表达式运算符=~
。
发布于 2008-10-23 20:10:53
如果您更喜欢正则表达式方法:
string='My string';
if [[ $string =~ "My" ]]; then
echo "It's there!"
fi
发布于 2008-10-23 12:47:04
我不确定是否使用if语句,但您可以使用case语句获得类似的效果:
case "$string" in
*foo*)
# Do stuff
;;
esac
https://stackoverflow.com/questions/229551
复制相似问题