use regular expression in if-condition in bash

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

    @OP,

    Is glob pettern not only used for file names?

    No, "glob" pattern is not only used for file names. you an use it to compare strings as well. In your examples, you can use case/esac to look for strings patterns.

     gg=svm-grid-ch 
     # looking for the word "grid" in the string $gg
     case "$gg" in
        *grid* ) echo "found";;
     esac
    
     # [[ $gg =~ ^....grid* ]]
     case "$gg" in ????grid*) echo "found";; esac 
    
     # [[ $gg =~ s...grid* ]]
     case "$gg" in s???grid*) echo "found";; esac
    

    In bash, when to use glob pattern and when to use regular expression? Thanks!

    Regex are more versatile and "convenient" than "glob patterns", however unless you are doing complex tasks that "globbing/extended globbing" cannot provide easily, then there's no need to use regex. Regex are not supported for version of bash <3.2 (as dennis mentioned), but you can still use extended globbing (by setting extglob ). for extended globbing, see here and some simple examples here.

    Update for OP: Example to find files that start with 2 characters (the dots "." means 1 char) followed by "g" using regex

    eg output

    $ shopt -s dotglob
    $ ls -1 *
    abg
    degree
    ..g
    
    $ for file in *; do [[ $file =~ "..g" ]] && echo $file ; done
    abg
    degree
    ..g
    

    In the above, the files are matched because their names contain 2 characters followed by "g". (ie ..g).

    The equivalent with globbing will be something like this: (look at reference for meaning of ? and * )

    $ for file in ??g*; do echo $file; done
    abg
    degree
    ..g
    

提交回复
热议问题