在 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 个字符串,str
和 substr
。我们应用了一个 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
输出:
使用 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
输出:
使用正则表达式运算符 (~=
)(方法 4)
还有另一个称为 regex operator
(~=) 的运算符,我们可以用它比较两个字符串以及字符串是否包含子字符串。
脚本:
#!/bin/bash
str='This is a bash tutorial'
substr='bash'
if [[ "$str" =~ .*"$substr".* ]]; then
echo "String contains the substring"
fi
请注意,在条件语句中,正则表达式运算符使右侧字符串成为正则表达式,符号 .*
表示比较字符串中出现的 0 次或多次子字符串。
输出:
因此,你可以看到几种从字符串中查找子字符串的方法。
相关文章
在 Bash 中运行 find -exec 命令
发布时间:2024/03/14 浏览次数:127 分类:操作系统
-
本文将演示如何使用 find 命令的 -exec 参数来使用 find 命令定位文件中的任何文本。