迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 >

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

作者:迹忆客 最近更新:2023/03/17 浏览次数:

从字符串中查找子字符串是最常用的字符串操作。有很多方法可以执行此任务。

在本文中,我们将看到多个基于 Bash 脚本的实现来查找给定字符串是否包含特定子字符串。

使用 case 条件语句(方法 1)

case 是 bash 中的条件语句,可用于在脚本中实现条件块。此语句可用于在 bash 中查找子字符串。

脚本:

#!/bin/bash

str='This is a bash tutorial'
substr='bash'

case $str in

  *"$substr"*)
    echo  "str contains the substr"
    ;;
esac

我们有 2 个字符串,strsubstr。我们应用了一个 case 语句来查找 str 是否包含 substr

输出:

用例条件语句

if 语句中使用通配符(方法 2)

我们还可以在 if 语句中使用通配符从字符串中查找子字符串。查找子字符串的最简单方法是将通配符星号 (*) 放在子字符串周围并将其与实际字符串进行比较。

脚本:

#!/bin/bash

str='This is a bash tutorial'
substr='tutorial'
if [[ "$str" == *"$substr"* ]]; then
  echo "String contains the sunstring"
else
  echo "String does'nt contains the substring"
fi

输出:

在 if 语句中使用通配符

使用 Bash 的 grep 命令(方法 3)

grep 命令也用于从文件或字符串中查找内容。它有一个选项 -q,它告诉 grep 命令不显示输出;返回

脚本:

#!/bin/bash

str='This is a bash tutorial'
substr='tutorial'
if grep -q "$substr" <<< "$str"; then
  echo "String contains the substring"
fi

输出:

使用 Bash 的 grep 命令

使用正则表达式运算符 (~=)(方法 4)

还有另一个称为 regex operator (~=) 的运算符,我们可以用它比较两个字符串以及字符串是否包含子字符串。

脚本:

#!/bin/bash

str='This is a bash tutorial'
substr='bash'
if [[ "$str" =~ .*"$substr".* ]]; then
  echo "String contains the substring"
fi

请注意,在条件语句中,正则表达式运算符使右侧字符串成为正则表达式,符号 .* 表示比较字符串中出现的 0 次或多次子字符串。

输出:

使用正则表达式运算符

因此,你可以看到几种从字符串中查找子字符串的方法。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便