[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to match regex in bash? (any character)

From: John Reiser
Subject: Re: How to match regex in bash? (any character)
Date: Mon, 26 Sep 2011 19:49:03 -0700
User-agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv: Gecko/20110906 Fedora/3.1.14-1.fc14 Thunderbird/3.1.14

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  
              precedence  as  == and !=.  When it is used, the string to the 
              of the operator is considered an  extended  regular  expression  
              matched  accordingly (as in regex(3)).  The return value is 0 if 
              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

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 
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 
or to use a variable:
              pattern="xxx.txt"   # a 7-character string
              [[ $1 =~ $pattern ]]   # the dot '.' in $pattern is a 
Example: using all literals in an instance of bash:
               $ [[ xxxxtxt =~ xxx.txt ]] && echo true

Also notice that quotes are not needed around the left-hand side  $1 :
              ting and pathname expansion are not performed on the  words  
              the  [[  and  ]] ...

Thus there is no need to use quotation marks to suppress word splitting
inside double brackets [[ ... ]].


reply via email to

[Prev in Thread] Current Thread [Next in Thread]