How do I match PATTERN but not PREFIX_PATTERN?

2019-07-19 18:42发布

问题:

Say I've got some documents that contain several lines with KEYWORD and some lines with PREFIX_KEYWORD.

How would I match only these lines that have KEYWORD and ignore the lines that have PREFIX_KEYWORD on them?

Yes, I could grep for KEYWORD, feed the results into the editor of my choice and let the editor delete all lines that have PREFIX_KEYWORD but I'm asking whether there's a built-in way in grep to do this.

If this helps: I'm not interested in the exact match but only want to know whether there are occurrences of KEYWORD in the file.

回答1:

One way would be to grep for your KEYWORD and filter out the rest. This could look like

grep KEYWORD file | grep -v PREFIX_KEYWORD

Another way with a perl expression:

grep -P '(?<!PREFIX_)KEYWORD' file

The same answer was given here: Regex to match specific strings without a given prefix



回答2:

Try this:

grep -w KEYWORD your_file

man page for -w says:

 -w    Searches for the expression as a word as if surrounded
       by \< and \>.


回答3:

If you need the word KEYWORD by itself, why not regex for KEYWORD with any special character before (space, newline, etc.)?



标签: regex grep