On Mon, Sep 26, 2011 at 9:49 PM, John Reiser <jrei...@bitwagon.com> wrote: > Peng Yu wrote: >> I know that I should use =~ to match regex (bash version 4). >> >> However, the man page is not very clear. I don't find how to match >> (matching any single character). For example, the following regex >> doesn't match xxxxtxt. Does anybody know how to match any character >> (should be '.' in perl) in bash. >> >> [[ "$1" =~ "xxx.txt" ]] > > The manual page for bash says that the rules of regex(3) apply: > > An additional binary operator, =~, is available, with the > same > precedence as == and !=. When it is used, the string to the > right > of the operator is considered an extended regular expression > and > matched accordingly (as in regex(3)). The return value is 0 if > the > string matches the pattern, and 1 otherwise. > and also: > Any part of the pattern may be quoted to force it to be matched > as a > string. > > Thus in the expression [[ "$1" =~ "xxx.txt" ]] the fact that the pattern > is quoted [here the whole pattern appears within double quotes] has turned the > dot '.' into a plain literal character, instead of a meta-character which > matches > any single character. > > The usual method of avoiding quotes in the pattern is to omit them: > [[ $1 =~ xxx.txt ]] # the dot '.' in the pattern is a > meta-character > or to use a variable: > pattern="xxx.txt" # a 7-character string > [[ $1 =~ $pattern ]] # the dot '.' in $pattern is a > meta-character > Example: using all literals in an instance of bash: > $ [[ xxxxtxt =~ xxx.txt ]] && echo true > true > $ > > Also notice that quotes are not needed around the left-hand side $1 : > Word > split‐ > ting and pathname expansion are not performed on the words > between > the [[ and ]] ... > > Thus there is no need to use quotation marks to suppress word splitting > inside double brackets [[ ... ]].
Thanks for the clarifications of all the replies. Now the manual makes much more sense to me. -- Regards, Peng