如何检查字符串是否在Bash中包含子字符串

编程入门 行业动态 更新时间:2024-10-15 06:18:06
本文介绍了如何检查字符串是否在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中包含子字符串

本文发布于:2023-11-29 16:09:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646898.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   Bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!