grep选择包含某些单词的字符串

时间:2012-11-20 08:33:23

标签: regex 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

3 个答案:

答案 0 :(得分:2)

尝试这样做:

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

如果您没有-E切换(代表 ERE Extented Regex Expression ):

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

<强>输出

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

对于匹配grep的行或结束时匹配Field[0-9]的行,RepeatLeft将为{{1}}。这是你期望的吗?

答案 1 :(得分:1)

我不太清楚如何使用grep达到你的目的。可能你想要Perl:

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

答案 2 :(得分:-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查看其工作原理。

相关问题