0

Suppose I have search the string which give like the following result

anything1.knownKeyWord anything2.knownKeyWord anything3[1].knownKeyWord 

How I can write generic syntax for grep such it match all 3 string. I have done like this

^.*\w+\d[\[]?[0]?[\]]?\.knownKeyWord.*$ 

But I think for indexing eg [1] is not written in good way, how can I achieve so that even i replace [1] with [2342jdsjf], I don't have to change the syntax much.

2 Answers 2

0

Using an extended regular expression:

$ grep -E '[[:alnum:]_]+[[:digit:]]+(\[[^]]+\])?\.knownKeyWord' <file anything1.knownKeyWord anything2.knownKeyWord anything3[1].knownKeyWord 

This would extract any line containing a string on the format

XXXNNN[YYY].knownKeyWord 

or

XXXNNN.knownKeyWord 

where XXX is any non-empty alphanumeric string (that may also include _), NNN is any string of (one or more) digits, and YYY is anything not including a ].

Use grep with -x if matches are to be complete lines. Use -w if matches are supposed to be complete words (i.e. not as a substring of something else).


Just using sed to show what each part of the regular expression is matching:

$ sed -E 's/([[:alnum:]_]+)([[:digit:]]+)(\[[^]]+\])?(\.knownKeyWord)/<\1><\2><\3><\4>/' <file <anything><1><><.knownKeyWord> <anything><2><><.knownKeyWord> <anything><3><[1]><.knownKeyWord> 
0

Try this,

grep -w 'knownKeyWord$' file.txt 

From man

-w, --word-regexp

 Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word- constituent characters are letters, digits, and the underscore. 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.