2012-11-20 48 views
1

我有一個列表:grep來選擇字符串包含特定單詞

/device1/element1/CmdDiscovery 
/device1/element1/CmdReaction 
/device1/element1/Direction 
/device1/element1/MS-E2E003-COM14/Field2 
/device1/element1/MS-E2E003-COM14/Field3 
/device1/element1/MS-E2E003-COM14/NRepeatLeft 

我怎樣才能grep,這樣只含"Field" followed by digits或者乾脆NRepeatLeft在串年底返回的字符串(在我的例子它會是最後三個字符串)

預期輸出:

/device1/element1/MS-E2E003-COM14/Field2 
/device1/element1/MS-E2E003-COM14/Field3 
/device1/element1/MS-E2E003-COM14/NRepeatLeft 

回答

1

試着這樣做:

grep -E "(Field[0-9]*|NRepeatLeft$)" file.txt 
     | |   |   || 
     | |   OR end_line | 
     | opening_choice closing_choice 
extented_grep 

如果你沒有-E開關(代表ERE推廣的正則表達式表達):

grep "\(Field[0-9]*\|NRepeatLeft$\)" file.txt 

OUTPUT

/device1/element1/MS-E2E003-COM14/Field2 
/device1/element1/MS-E2E003-COM14/Field3 
/device1/element1/MS-E2E003-COM14/NRepeatLeft 

這將grep匹配Field[0-9]或在端部匹配RepeatLeft線線路。這是你期望的嗎?

-1
$ grep -E '(Field[0-9]*|NRepeatLeft)$' file.txt 

輸出:

/device1/element1/MS-E2E003-COM14/Field2 
/device1/element1/MS-E2E003-COM14/Field3 
/device1/element1/MS-E2E003-COM14/NRepeatLeft 

說明:

Field  # Match the literal word 
[0-9]*  # Followed by any number of digits 
|   # Or 
NRepeatLeft # Match the literal word 
$   # Match the end of the string 

你可以看到這是如何工作與你的例子here

+0

ERE不是PCRE或Perl,'(:)'是不是一個有效的結構?在ERE。 –

1

我沒有太大把握的如何使用您的purpose.Probably的grep你想的Perl此:

perl -lne 'if(/Field[\d]+/ or /NRepeatLeft/){print}' your_file 
相關問題