glossy
glossy

Reputation: 57

grep to select strings that contains certain words

I have a list:

/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

How can I grep so that the returned strings containing only "Field" followed by digits or simply NRepeatLeft at the end of string (in my example it will be the last three strings)?

Expected output:

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

Upvotes: 1

Views: 886

Answers (3)

Vijay
Vijay

Reputation: 67319

I am not much sure of how to use grep for your purpose.Probably you would like perl for this:

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

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185881

Try doing this :

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

if you don't have -E switch (stands for ERE : Extented Regex Expression):

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

That will grep for lines matching Field[0-9] or lines matching RepeatLeft at the end. Is it what you expect ?

Upvotes: 2

Chris Seymour
Chris Seymour

Reputation: 85913

$ grep -E '(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

Explanation:

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 

You can see how this works with your example here.

Upvotes: -1

Related Questions