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

问:

在 Bash 中一个字符串如下:

bash 复制代码
string="My string"

如何测试它是否包含另一个字符串?

bash 复制代码
if [ $string ?? 'foo' ]; then
  echo "It's there!"
fi

其中 ?? 是我不知道的运算符。我该使用 echo 和 grep 吗?

bash 复制代码
if echo "$string" | grep 'foo'; then
  echo "It's there!"
fi

这看起来有点笨拙。


答1:

我不确定是否可以使用 if 语句,但你可以使用 case 语句得到类似的效果:

bash 复制代码
case "$string" in 
  *foo*)
    # Do stuff
    ;;
esac

答2:

如果使用双方括号,也可以在 case 语句之外使用 Marcus 的答案(* 通配符):

bash 复制代码
string='My long string'
if [[ $string == *"My long"* ]]; then
  echo "It's there!"
fi

请注意,中间有空格的字符串需要放在双引号之间,* 通配符应该在外面。还要注意,这里使用了一个简单的比较操作符(即 ==),而不是正则表达式操作符 =~。


答3:

如果你更喜欢正则表达式的方法:

bash 复制代码
string='My string';

if [[ $string =~ "My" ]]; then
   echo "It's there!"
fi

更多解决思路的回答参考:https://stackoverflow.com/a/20460402

简单的函数:

bash 复制代码
stringContain() { [ -z "$1" ] || { [ -z "${2##*$1*}" ] && [ -n "$2" ];};}

这样可以测试空字符串的情况:

bash 复制代码
$ if stringContain '' ''; then echo yes; else echo no; fi
yes
$ if stringContain 'o "M' ''; then echo yes; else echo no; fi
no

参考:stackoverflow question 229551


相关阅读:

相关推荐
Shylock_Mister4 小时前
Linux C线程编程全指南
linux·运维·c语言
心灵宝贝4 小时前
CentOS 7 安装 unzip-6.0-21.el7.x86_64.rpm 步骤详解(附安装包)
linux·服务器·centos
q***13344 小时前
在linux(Centos)中Mysql的端口修改保姆级教程
linux·mysql·centos
Autism....4 小时前
服务器理解
运维·服务器
Starry_hello world4 小时前
Linux 文件缓冲区
linux
天亮之前_ict4 小时前
【故障排查】intel 服务器安装Win server 2019蓝屏解决方法
运维·服务器
牢七5 小时前
操作系统。
linux
SongYuLong的博客5 小时前
openwrt源码编译环境搭建-安装Luci
linux·嵌入式硬件
熙客5 小时前
Linux:监控命令
linux·运维
飞鱼&5 小时前
Linux 常用命令
linux·运维·服务器