2014-07-17 45 views
1

我正在寻找类的实例,例如Foo除了导入。也就是说,比赛应该如下。grep表示行不以其他模式开始的模式

import com.acme.Foo; // Does not match 
... 
import com.acme.FooBar; // Does not match 
... 
    static Foo FOO = new Foo(); // matches 
    ... 
    Foo f = new Foo(); // matches 
    FooBar.newFoo(); // matches 

我想这可以用perl正则表达式来完成,带有负向lookbehind?我不知道perl在所以我使用grep --perl-regexp,但无法弄清楚,主要是因为我不知道perl regexps也很好。我只能拿出以下内容,这两者都不起作用:

grep --perl-regexp -nH '(?<!import).*Foo' t #matches all lines 
grep --perl-regexp -nH '(?<!import .*)Foo' t #error: lookbehind assertion is not fixed length 

我打开使用perl以及给定的确切命令来使用。

编辑:顺便说一句,有趣的是,Perl的答案是从用户使用适当的神秘和简洁的名字 - HWND和ZX81 :)

回答

1

而不是使用负回顾后的,使用Negative Lookahead

grep -P '^(?!.*import).*Foo' t 

或者您可以使用Perl单线程。

perl -ne 'print if /^(?!.*import).*Foo/' t 
1

以您目前的输入,您可以使用此:

grep -oP "^(?!.*import).*new ?\KFoo()" your path 

匹配只是Foo

如果你想整条生产线,

grep -P "^(?!.*import).*new ?Foo()" your path 
1

为什么不直接使用两个grep S:

grep "Foo" file(s) | grep -v "import" 
+0

这就是我在做什么,直到我得到这个答案,但它会歪斜grep的输出因为我也在使用'--before-context' –