本文介绍了如何在 Bash 中检查字符串是否包含子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 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其中 ?? 是我的未知运算符.我使用 echo 和 grep 吗?
Where ?? is my unknown operator. Do I use echo and grep?
if echo "$string" | grep 'foo'; then echo "It's there!" fi这看起来有点笨拙.
推荐答案您可以使用 Marcus 的回答(* 通配符)在 case 语句之外,如果您使用双括号:
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. Also note that a simple comparison operator is used (i.e. ==), not the regex operator =~.
更多推荐
如何在 Bash 中检查字符串是否包含子字符串
发布评论