gpt4 book ai didi

string - 如何检查字符串是否包含 Bash 中的子字符串

转载 作者:行者123 更新时间:2023-11-29 08:36:41 27 4
gpt4 key购买 nike

我在 Bash 中有一个字符串:

string="My string"

如何测试它是否包含另一个字符串?

if [ $string ?? 'foo' ]; then
echo "It's there!"
fi

?? 是我未知的运算符。我是否使用 echogrep

if echo "$string" | grep 'foo'; then
echo "It's there!"
fi

这看起来有点笨拙。

最佳答案

您可以使用 Marcus's answer (* wildcards)如果您使用双括号,也在 case 语句之外:

string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi

注意needle字符串中的空格需要放在双引号之间,*通配符要在外面。另请注意,使用了一个简单的比较运算符(即 ==),而不是正则表达式运算符 =~

关于string - 如何检查字符串是否包含 Bash 中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/229551/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com