您的当前位置:首页正文

Shell中的字符串包含

来源:要发发知识网

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