views:

37

answers:

2

I have a sentence that I want to write a shell command to grep it from a text: The sentence is:

self.timeout=2.0

However, as this is a part of code from a file. so it this sentence could also be

self.timeout = 2.0

or

self.timeout =2.0

or

self.timeout = 8.0

that is: there may be blanks besides "=", and the value of self.timeout maybe different.

So could anybody help to give me a regex in shell command. Anyway, I know the shell:

grep "self.timeout*="

works. But I think it is not a good regex in shell command.

Thanks a lot!

+4  A: 

I'd do:

grep -E 'self\.timeout[ \t]*=[ \t]*[0-9.]+'

note:

      |      |          |  |           
  use egrep  |          | zero or more
             |    whitespace
             |
  make sure we're matching
     a dot instead of
      "any character"     
slebetman
slebetman, many thanks!Yes, this regex works. Your regex is much formal than mine!Thanks!
zhaojing
Good catch on the `\.`
John Kugelman
slebetman,many thanks for your detailed note. It makes me much better understand your regex. I found stackoverflow is really a good website!
zhaojing
+1 for the vertical lines. Hard-work should always be rewarded ;-)
gawi
Yes, I agree with gawi.Thanks for slebetman.
zhaojing
+2  A: 

Using grep -E aka egrep you can use a regular expression, with which the * operator will match 0 or more of the preceding character:

egrep 'self\.timeout *='

Or use [[:space:]] to match all whitespace characters:

egrep 'self\.timeout[[:space:]]*='
John Kugelman
John, many thanks for your always quick answers.The * operator will match 0 or more of the preceding character.Yes, in fact, it is the answer I want!I remember * can solve the problem, but I can't remember clearly.Thanks a lot!And many thanks for your second method!
zhaojing