2014-07-17 42 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' –