String contains in Bash
I have a string in Bash:
string="My string"
How can I test if it contains another string?
if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
Where ??
is my unknown operator. Do I use echo and grep
?
if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
That looks a bit clumsy.
You can use Marcus's answer (* wildcards) outside a case statement, too, if you use double brackets:
string='My long string'
if [[ $string = *"My long"* ]]; then
echo "It's there!"
fi
Note that spaces in the needle string need to be placed between double quotes, and the *
wildcards should be outside.
如果你喜欢正则表达式的方法:
string='My string';
if [[ $string =~ .*My.* ]]
then
echo "It's there!"
fi
我不确定使用if语句,但是您可以通过case语句获得类似的效果:
case "$string" in
*foo*)
# Do stuff
;;
esac
链接地址: http://www.djcxy.com/p/924.html
上一篇: HEAD在Git中
下一篇: 字符串包含在Bash中