=Start=
搜索关键字:
- linux shell string contain
参考链接:
- http://stackoverflow.com/questions/229551/string-contains-in-bash
- http://stackoverflow.com/questions/4277665/how-do-i-compare-two-string-variables-in-an-if-statement-in-bash
- http://stackoverflow.com/questions/2829613/how-do-you-tell-if-a-string-contains-another-string-in-unix-shell-scripting
- http://codingstandards.iteye.com/blog/1181490
- http://www.cnblogs.com/chengmo/archive/2010/10/02/1841355.html
参考解答:
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 条评论
shell中的字符串不等于
http://unix.stackexchange.com/questions/67898/using-the-not-equal-operator-for-string-comparison
`
if [ “$PHONE_TYPE” != “NORTEL” ] && [ “$PHONE_TYPE” != “NEC” ] && [ “$PHONE_TYPE” != “CISCO” ]; then
:
else
:
fi
或
if [[ $PHONE_TYPE =~ ^(NORTEL|NEC|CISCO)$ ]]; then
echo “Phone type must be nortel, cisco or nec.”
fi
`