Shell中的字符串包含

本文最后更新于2015年11月7日,已超过 1 年没有更新,如果文章内容失效,还请反馈给我,谢谢!

=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=

声明: 除非注明,ixyzero.com文章均为原创,转载请以链接形式标明本文地址,谢谢!
https://ixyzero.com/blog/archives/2519.html

One thought on “Shell中的字符串包含”

发表评论

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