雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

linux的shell脚本中如何在一个字符串中查找指定字符串是否存在

2024-08-23 27

摘要

在Linux中写Shell脚本,经常会遇到需要在字符串中查找和判断指定的子字符串是否存在,通配符,正则表达式,grep命令等都是常用的方法,以下整理几种shell脚本查找字符串的方法示例。

利用grep命令

示例代码如下:

strA=long string
strB=string
result=$(echo $strA | grep ${strB})
if [[ $result !=  ]]
then
    echo 包含
else
    echo 不包含
fi

先打印长字符串,然后在长字符串中通过grep命令查找要搜索的字符串,用变量result记录搜索的结果,如果结果不为空,说明strA包含strB。如果结果为空,说明不包含。
这个方法充分利用了grep 的特性,最为简洁。

利用shell的字符串运算符

#!/bin/bash
strA=helloworld
strB=low
if [[ $strA =~ $strB ]]
then
    echo 包含
else
    echo 不包含
fi

利用通配符

用星号通配符(星号)*包围子字符串并将其与字符串进行比较是最简单的方法。

通配符表示零个,一个或多个字符的符号。
如果子字符串包含在字符串中返回true。

在下面的示例中,我们使用if语句和相等运算符(==)来检查字符串 STR 中是否找到子字符串 SUB:

#!/bin/bash
A=helloworld
B=low
if [[ $A == *$B* ]]
then
    echo exist
else
    echo not exist
fi

执行结果输出:

exist

利用case in 语句

您也可以使用case语句来检查字符串是否包含另一个字符串,而不是使用if语句。

#!/bin/bash
thisString=1 2 3 4 5 # 源字符串
searchString=1 2 # 搜索字符串
case $thisString in 
    *$searchString*) echo exist ;;
    *) echo not exist ;;
esac

执行结果输出:

exist

利用Shell的替换语法

利用shell语法的替换功能搜索:

#!/bin/bash
STRING_A=hello word
STRING_B=llo
if [[ ${STRING_A/${STRING_B}//} == $STRING_A ]]
then
    echo N
else
    echo Y
fi

使用正则表达式运算符

可以使用正则表达式运算符=~确定指定子字符串是否出现在字符串中。 使用此运算符时,右字符串被视为正则表达式。
周期后跟星号*匹配除了换行符之外的任何字符零次或多次出现。

#!/bin/bash

STR=hello cfnotes 2022.
SUB=cfnotes

if [[ $STR =~ .*$SUB.* ]]; then
  echo Im there.
fi

脚本将输出如下内容:

Im there.

其他方法

以下再列举shell中查找字符串的其他几个方法。

#! /bin/bash
 
var1=hello
var2=he
#方法1
if [ ${var1:0:2} = $var2 ]
then
    echo 1:include
fi
#方法2
echo $var1 |grep -q $var2
if [ $? -eq 0 ]
then
    echo 2:include
fi
#方法3
echo $var1 |grep -q $var2  echo include || echo not
#方法4
[[ ${var1/$var2/} != $var2 ]]  echo include || echo not
更新于:24天前
赞一波!4

文章评论

全部评论