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
  *ERROR*)
  # Do stuff
  echo "包含ERROR..."
  ;;
  *ORA-*)
  echo "包含bbb..."
  return 1
  ;;
  *) #若以上都不符合,则给出交互式提示并退出。
  usage
  return 0
  ;;
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

猜你喜欢

转载自www.cnblogs.com/wuyuanguo/p/11796940.html