Shell中的字符串包含


=Start=

搜索关键字:
  • linux shell string contain
参考链接:
参考解答:
1.通配符
string='My long string'
if [[ $string == *"My long"* ]]; then
  echo "It's there!"
fi
2.正则匹配
string='My long string'
if [[ $string =~ .*My.* ]]; then
   echo "It's there!"
fi
3.switch…case版本的通配符(速度最快……)
string='My long string'
case "$string" in
  *foo*)
    # Do stuff
    ;;
esac
4.用grep来实现
string='My long string'
if grep -q foo <<<$string; then
    echo "It's there"
fi
5.用字符串替换/删除来实现
string='My long string'
if [ "$string" != "${string/foo/}" ]; then
    echo "It's there!"
fi
性能比较:

http://stackoverflow.com/a/25535717

#!/bin/bash
# Author:	ixyzero.com
# Date:		2015-11-7
# set -x
# export PS4='+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: '

#echo "$@"
#echo "$*"
#LOGGER="N"
#options="$@"
#if [ "$options" != "${options/--log/}" ]; then
#    LOGGER="Y"
#fi

function stringContain() { [ -z "${2##*$1*}" ]; }

# [[ $b =~ $a ]]
# [ "${b/$a//}" = "$b" ]
# [[ $b == *$a* ]]
# case $b in *$a) : ;; esac
# stringContain $a $b

/usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do [[ $b =~ $a ]] ; x=$(($x-1)); done'
sleep 2
/usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do [ "${b/$a//}" = "$b" ] ; x=$(($x-1)); done'
sleep 2
/usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do [[ $b == *$a* ]] ; x=$(($x-1)); done'
sleep 2
/usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do case $b in *$a) : ;; esac ; x=$(($x-1)); done'
sleep 2
/usr/bin/time bash -c 'function stringContain() { [ -z "${2##*$1*}" ]; }; a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do stringContain $a $b ; x=$(($x-1)); done'
sleep 2
/usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do [ -z "${b##*$a*}" ] ; x=$(($x-1)); done'
sleep 2
/usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do [ "$b" != "${b/$a/}" ] ; x=$(($x-1)); done'

=EOF=


《“Shell中的字符串包含”》 有 1 条评论

发表回复

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