📌  相关文章
📜  bash 检查字符串是否包含子字符串 - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:29:35.567000             🧑  作者: Mango

Bash 检查字符串是否包含子字符串

在Bash中,我们经常需要检查一个字符串是否包含另一个子字符串。以下是几种方法:

方法一:使用“grep”命令

我们可以使用“grep”命令来搜索字符串中是否包含子字符串。以下是使用“grep”的示例代码:

string="hello world"
if [[ $string =~ "hello" ]]; then
    echo "Contains 'hello'"
fi

这将检查字符串“hello world”是否包含子字符串“hello”。如果包含,它会输出“Contains 'hello'”。

方法二:使用“[[...]]”运算符

Bash还提供了一个“[[...]]”运算符,我们可以使用它来测试字符串是否包含子字符串。以下是代码示例:

string="hello world"
if [[ "$string" == *"hello"* ]]; then
    echo "Contains 'hello'"
fi

这将检查字符串“hello world”是否包含子字符串“hello”。如果包含,它会输出“Contains 'hello'”。

方法三:使用“case”语句

我们可以使用“case”语句来检查字符串是否包含子字符串。以下是示例代码:

string="hello world"
case "$string" in 
    *hello*) 
        echo "Contains 'hello'" ;;
esac

这将检查字符串“hello world”是否包含子字符串“hello”。如果包含,它会输出“Contains 'hello'”。

方法四:使用“if”语句和“expr”命令

我们也可以使用“if”语句和“expr”命令来检查字符串是否包含子字符串。以下是示例代码:

string="hello world"
if expr match "$string" ".*hello.*" >/dev/null; then
    echo "Contains 'hello'"
fi

这将检查字符串“hello world”是否包含子字符串“hello”。如果包含,它会输出“Contains 'hello'”。

以上是几种常见的方法来检查字符串是否包含子字符串。您可以根据实际情况选择适合您的方法。