tags:

views:

57

answers:

3

I'm looking in our code for something that looks very much like:

#$foo="bar";
$foo="baz";

Problems:

  1. I don't know the name of the variable
  2. I don't know which line is actually commented out.
  3. I really don't seem to be able to properly write a multi-line regex.

My initial attempt was ack /\$(.\*)=.\*$\$($1)=/

I prefer ack usually for code grepping, but I don't mind using grep either. JWZ probably thinks I have way more than 2 problems by now.

A: 

I don't exactly understand your matching rules, but this regex should show the direction:

^#\$(\w+)=.*?\$(\1)=

// [x] ^$ match at line breaks
// [x] Dot matches all

Usually grepdoesn't support multiline matching.

splash
A: 

This might work:

^#?(\$\w+)\s*=.*[\r\n]+#?\1\s*=.*$

Explanation:

^            start of line
#?           optional comment
(\$\w+)      $, followed by variable name, captured into backreference no. 1
\s*          optional whitespace
=            =
.*           any characters except newline
[\r\n]+      one or more newlines (\r thrown in for safety)
#?           optional comment
\1           same variable name as in the last line
\s*=.*       as above
$            end of line

This does not check that exactly one of the lines is commented out (it will also match if none or both are). If that is a problem, let me know.

I don't know if grep can be made to match multiple lines in a single regex; whatever tool you're using should be set to the "^/$ match start/end of line" mode (instead of start/end of string).

Tim Pietzcker
+1  A: 

Neither grep nor ack will handle more than one line at a time.

Andy Lester
Looks like you're right, nothing else I've tried works.
Neth