use regular expression in if-condition in bash

前端 未结 5 608
盖世英雄少女心
盖世英雄少女心 2020-12-02 09:28

I wonder the general rule to use regular expression in if clause in bash?

Here is an example

$ gg=svm-grid-ch  
$ if [[ $gg == *grid* ]] ; then echo         


        
5条回答
  •  隐瞒了意图╮
    2020-12-02 10:12

    Adding this solution with grep and basic sh builtins for those interested in a more portable solution (independent of bash version; also works with plain old sh, on non-Linux platforms etc.)

    # GLOB matching
    gg=svm-grid-ch    
    case "$gg" in
       *grid*) echo $gg ;;
    esac
    
    # REGEXP    
    if echo "$gg" | grep '^....grid*' >/dev/null ; then echo $gg ; fi    
    if echo "$gg" | grep '....grid*' >/dev/null ; then echo $gg ; fi    
    if echo "$gg" | grep 's...grid*' >/dev/null ; then echo $gg ; fi    
    
    # Extended REGEXP
    if echo "$gg" | egrep '(^....grid*|....grid*|s...grid*)' >/dev/null ; then
      echo $gg
    fi    
    

    Some grep incarnations also support the -q (quiet) option as an alternative to redirecting to /dev/null, but the redirect is again the most portable.

提交回复
热议问题