如何在 Bash 中检查字符串是否包含子字符串 [英] How to check if a string contains a substring in Bash

查看:37
本文介绍了如何在 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

其中 ?? 是我的未知运算符.我使用 echogrep 吗?

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 中检查字符串是否包含子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆