zl程序教程

您现在的位置是:首页 >  其他

当前栏目

在 bash 脚本中如何检查一个字符串是否包含另一个字符串

2023-02-25 18:02:01 时间

我们在写 bash 脚本的时候,假如有一个字符串,我们想检查其中是否包含另一个子字符串,那这个时候需要怎样做呢?

在 bash 脚本中,有不止一种检查子字符串的方法,我们今天介绍一些简单的例子,然后在分享一个常用的 bash 脚本。

使用if-else语句检查bash中的子字符串

如果您熟悉bash中的条件语句,可以使用它以以下方式检查字符串是否包含子字符串:

if [[ $fullstring == *"$substr"* ]];

一个简单的例子

上面的脚本中使用了双括号,这是有必要的,它是一种原生的方式,因为它没有使用任何其他工具。下面我们举个例子来对上面的脚本做一下解释。

使用长字符串初始化变量:

$ fullstring="This is a string with a stretch"

然后,将字符串“stretch”存储在变量 substr 中:

$ substr="stretch"

再然后进行字符串比较:

$ if [[ $fullstring == *"$substr"* ]]; then

这里的星号 * 表示零个或多个字符。大家应该熟悉 bash 脚本中引号的概念,引号内的 $substr 将其替换为真实的值。

基本上,上述脚本是检查完整的字符串是否与 xxxxxxsubstrxxxxxx 类型的字符串匹配。

另外,也可以直接使用子字符串,而不是通过变量:

$ if [[ $fullstring == "stretch" ]]; then

下面我们使用 else 语句完成这个脚本,如果找不到子字符串,该语句将显示另一条消息:

#!/bin/bash
fullstring="This is a string with a stretch"
substr="stretch"
if [[ $fullstring == *"$substr"* ]]; then
echo "Found $substr!"
else
echo "$substr not found!"
fi

运行上述脚本,将会找到子字符串:

$ bash ​​substr.sh​​
Found stretch!

另一个例子

子字符串在脚本中非常有助于与用户交互。使用 read 命令可以让 bash 脚本接受用户的输入。

echo "Hey there..what is your name?"
read Name
echo "Hello "$name"! The Matrix Resurrections trailer is here! Is your pill Red or Blue?"
read Pill
if [[ $Pill == "Red" || Name"!"
echo "Welcome..to the real world "$Name"!"
else
echo "Wake Up "$Name"!"
fi

授予它可执行权限并执行脚本:

$ chmod +x ​​makeyourchoice.sh​​
$ ./makeyourchoice.sh

其输出如下所示:

Hey there..what is your name?
avimanyu
Hello avimanyu! The Matrix Resurrections trailer is here! Is your pill Red or Blue?
I have Red pill
Welcome..to the real world avimanyu!

在上面的脚本中,我们使用 if 语句以考虑两种可能性(区分大小写)。Red 是一种可能的输入,但是 red(小写)也是一种可能性,所以我们添加了另一个条件,|| 表示 “或”,如果输入为 Red,则它是一个子字符串。即使 red(小写)不是用户输入,我们也需要 在脚本中添加上它。

使用 grep 命令 在 bash 中查找子字符串

这是在bash中查找字符串中的子字符串的另一种方法。按以下方式使用grep命令:

if grep -q "$substr" <<< "$fullstring"; then echo "Found"; fi

选项 -q 表示 grep 将处于安静模式(quiet mode),不显示任何输出。另外需要注意,有 3 个 <,而不是 2 个。