菜鸟笔记
提升您的技术认知

shell判断字符串包含关系的三种方法-ag真人游戏

#!/bin/bash
#string include
str_short="hello"
str_long="hello,shell!"
# grep查找法
function test1 ()
{
	echo -e "test1:\c"
	result=$(echo $str_long | grep "${str_short}")
	if [[ "$result" != "" ]]; then
		echo "包含"
	else
		echo "不包含"
	fi
}
# 字符串运算符
function test2 ()
{
	echo -e "test2:\c"
	if [[ $str_long =~ $str_short ]]; then
		echo "包含"
	else
		echo "不包含"
	fi
}
# 利用通配符
function test3 ()
{
	echo -e "test3:\c"
	if [[ $str_long == *$str_short* ]]; then
		echo "包含"
	else
		echo "不包含"
	fi
}
test1
test2
test3
exit 0


网站地图