use regular expression in if-condition in bash

前端 未结 5 617
盖世英雄少女心
盖世英雄少女心 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:11

    When using a glob pattern, a question mark represents a single character and an asterisk represents a sequence of zero or more characters:

    if [[ $gg == ????grid* ]] ; then echo $gg; fi
    

    When using a regular expression, a dot represents a single character and an asterisk represents zero or more of the preceding character. So ".*" represents zero or more of any character, "a*" represents zero or more "a", "[0-9]*" represents zero or more digits. Another useful one (among many) is the plus sign which represents one or more of the preceding character. So "[a-z]+" represents one or more lowercase alpha character (in the C locale - and some others).

    if [[ $gg =~ ^....grid.*$ ]] ; then echo $gg; fi
    

提交回复
热议问题