描述
本文是希望通过 shell 语法判定字符串 str 中是否包含 subStr ,尝试使用 shell 来解决。
其中:
str="This is my test string search_string" #被测试字符串
subStr="search_" #待查找的字符串1
subStr2="search_TTT" #待查找的字符串2
具体实现方法
方法1
if [[ ${str} == *${subStr}* ]] ;then
echo -e "String '${str}' contain substring: '${subStr}'."
else
echo -e "String '${str}' don't contain substring: '${subStr}'."
fi
其中 [[ ... ]]
(注意两边有空格)是Bash在 2.02 版中, 引入的扩展测试命令,它以其他语言的程序员更熟悉的方式执行比较。
请注意 **[[ 是关键字**
,而不是命令。
使用 [[ … ]] 测试构造,而不是 [ … ] 可以防止脚本中的许多逻辑错误。 例如,&&、||、< 和 > 运算符在 [[ ]] 测试中工作,而在 [ ] 构造中给出错误。
具体可以参看 7.1. Test Constructs
方法2
if echo ${str} | grep ${subStr} ;then
echo -e "String '${str}' contain substring: '${subStr}'."
else
echo -e "String '${str}' don't contain substring: '${subStr}'."
fi
此种方式有个小的问题是,if
判定中 echo
会将 str
输出并打印到屏幕上去。可以考虑借用上面的关键字 [[
来改进:
if [[ $(echo ${str} | grep ${subStr}) ]];then
echo -e "String '${str}' contain substring: '${subStr}'."
else
echo -e "String '${str}' don't contain substring: '${subStr}'."
fi
方法3
if [[ ${str} =~ ${subStr} ]] ;then
echo -e "String '${str}' contain substring: '${subStr}'."
else
echo -e "String '${str}' don't contain substring: '${subStr}'."
fi
此种应用比较少见,主要是利用 =~
操作符。即对双括号内的正则表达式 进行匹配运算测试。(Perl 也有类似的运算符)。
#!/bin/bash
variable="This is a fine mess."
echo "$variable"
# Regex matching with =~ operator within [[ double brackets ]].
if [[ "$variable" =~ T.........fin*es* ]]
# NOTE: As of version 3.2 of Bash, expression to match no longer quoted.
then
echo "match found"
# match found
fi
或者
#!/bin/bash
input=$1
if [[ "$input" =~ "[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]" ]]
# ^ NOTE: Quoting not necessary, as of version 3.2 of Bash.
# NNN-NN-NNNN (where each N is a digit).
then
echo "Social Security number."
# Process SSN.
else
echo "Not a Social Security number!"
# Or, ask for corrected input.
fi
具体可以参看https://tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF
方法4
if [ -z "${str##*$subStr*}" ];then
echo -e "String '${str}' contain substring: '${subStr}'."
else
echo -e "String '${str}' don't contain substring: '${subStr}'."
fi
和下面的例子等价
if [ -z "${str%%*$subStr*}" ];then
echo -e "String '${str}' contain substring: '${subStr}'."
else
echo -e "String '${str}' don't contain substring: '${subStr}'."
fi
string='echo "My string"'
for reqsubstr in 'o "M' 'alt' 'str';do
if [ -z "${string##*$reqsubstr*}" ] ;then
echo "String '$string' contain substring: '$reqsubstr'."
else
echo "String '$string' don't contain substring: '$reqsubstr'."
fi
done
其中
#
是将${var}
中的左边(键盘上 #
在 $
的左边)的${Pattern}
去掉;
%
是将${var}
中的右边(键盘上 %
在 $
的右边)的${Pattern}
去掉;
其中单一符号#
或%
是最小匹配;两个符号##
或%%
则是最大匹配。
更多示例请参看:shell 的 ${ }中 ##、%%、// 使用方法及举例
Reference
HTML 版本:Advanced Bash-Scripting Guide
PDF 版本:Advanced Bash-Scripting Guide