Bash中如何判断字符串是否以某个字符(串)开头、包含、结尾?


=Start=

缘由:

最近在写一些功能性脚本,发现Bash中字符串的startwith/endwith/contain判断这些功能还是比较常用的,但Bash不像Python自带这些函数,所以需要自己整理总结一下,方便以后使用。

正文:

参考解答:

主要参考之前记录的文章:

&

  • 字符串的判等应该使用「=」或「==」符号;
  • 数字的判等才是使用「-eq」来进行(网上很多文章瞎写,也不验证一下……);
#!/bin/bash
# set -x

var="ixyzero.com is the best!"

function func_main() {
	# if [ $# -gt 0 ]; then
	# 	input="$1"
	# else
	# 	input="ixyzero.com"
	# fi
	input=${1:-"ixyzero.com"}
	echo $input
	
	# echo ${#input}	# ${#input} 是 $input 变量的长度
	if [ ${var:0:${#input}} = $input ]; then
		echo "\"$var\" startwith $input"
	else
		echo "\"$var\" not startwith $input"
	fi
}
func_main "$@"

=

# 测试/使用方法如下
#不带参数(使用默认值进行测试)
$ bash sh_str_startwith.sh
ixyzero.com
"ixyzero.com is the best!" startwith ixyzero.com
$
#主动传入参数1
$ bash sh_str_startwith.sh abc
abc
"ixyzero.com is the best!" not startwith abc
#主动传入参数2
$ bash sh_str_startwith.sh i
i
"ixyzero.com is the best!" startwith i

&

#!/bin/bash
# set -x

var="ixyzero.com is the best!"

function func_main() {
	# if [ $# -gt 0 ]; then
	# 	input="$1"
	# else
	# 	input="ixyzero.com"
	# fi
	input=${1:-"best!"}
	echo $input
	
	# echo ${#input}	# ${#input} 是 $input 变量的长度
	if [ ${var:0-${#input}} = $input ]; then
		echo "\"$var\" endwith $input"
	else
		echo "\"$var\" not endwith $input"
	fi
}
func_main "$@"

=

$ bash sh_str_endwith.sh
best!
"ixyzero.com is the best!" endwith best!
$
$ bash sh_str_endwith.sh best
best
"ixyzero.com is the best!" not endwith best
$
$ bash sh_str_endwith.sh !
!
"ixyzero.com is the best!" endwith !
$

&

# 字符串包含判断
# returns OK if $1 contains $2
strstr() {
  [ "${1#*$2*}" = "$1" ] && return 1
  return 0
}
参考链接:

=END=


《“Bash中如何判断字符串是否以某个字符(串)开头、包含、结尾?”》 有 2 条评论

回复 hi 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注