开发者

An ack or grep regex to match two lines, that are nearly the same

I'm looking in our code for something that looks very much开发者_如何学Python 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.


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


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).


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.


you can use -A or -B in grep to list the lines above or after that string you are looking for

$cat 1.txt
a
b
c
d
123
e
f
g
h
─$ grep 123 1.txt -A 3 -B 2
c
d
123
e
f
g

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜