shell 如何判断是否包含字符串
在 Shell 脚本中,可以使用多种方法来判断一个字符串是否包含另一个字符串。以下是几种常见的方法:
方法 1:使用 if 语句和 [[ ... ]] 条件表达式
string="Hello, World!"
substring="World"
if [[ "$string" == *"$substring"* ]]; then
echo "字符串包含 $substring"
else
echo "字符串不包含 $substring"
fi
方法 2:使用 case 语句
string="Hello, world!"
substring="world"
case "$string" in
*"$substring"*)
echo "字符串包含 $substring"
;;
*)
echo "字符串不包含 $substring"
;;
esac
方法 3:使用 grep 命令
string="Hello, world!"
substring="world"
if echo "$string" | grep -q "$substring"; then
echo "字符串包含 $substring"
else
echo "字符串不包含 $substring"
fi
方法 4:使用 [[ ... =~ ... ]] 正则表达式
string="Hello, world!"
substring="world"
if [[ "$string" =~ "$substring" ]]; then
echo "字符串包含 $substring"
else
echo "字符串不包含 $substring"
fi
方法 5:使用 awk 命令
string="Hello, world!"
substring="world"
if echo "$string" | awk -v sub="$substring" '{if (index($0, sub) > 0) print "字符串包含 " $sub; else print "字符串不包含 " $sub}'; then
:
fi
方法 6:使用 perl 命令
string="Hello, world!"
substring="world"
if perl -e 'print "字符串包含 $ARGV[0]\n" if $ARGV[1] =~ /$ARGV[0]/;' "$substring" "$string"; then
:
fi
方法 7:使用 python 命令
string="Hello, world!"
substring="world"
if python -c "print('字符串包含 $substring' if '$substring' in '$string' else '字符串不包含 $substring')"; then
:
fi
方法 6:使用 index 函数(仅限 bash
string="Hello, world!"
substring="world"
if [[ $(index "$string" "$substring") -gt 0 ]]; then
echo "字符串包含 $substring"
else
echo "字符串不包含 $substring"
fi