How do I match PATTERN but not PREFIX_PATTERN?

2019-07-19 18:09发布

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.

标签: regex grep
3条回答
我只想做你的唯一
2楼-- · 2019-07-19 18:40

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

查看更多
相关推荐>>
3楼-- · 2019-07-19 18:47

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

查看更多
混吃等死
4楼-- · 2019-07-19 18:48

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 \>.
查看更多
登录 后发表回答