使用 grep 搜索特定字符串

sun*_*khk 1 command-line grep

我想在具有特定字符串的文件中进行搜索,并仅显示与该字符串完全匹配的行,但这似乎不适用于grep -w.

这只是一个示例,因为我将在脚本中搜索字符串,然后只想显示那些完全匹配的行,而不是“string-xxxx”或“string.io”。

有人有什么主意吗?

root@ubuntu-client:/var/lib/apt/lists# cat aa
aide is good
this is aide one
that is aide-common good
aide-good is not ok
hello aide-help
root@ubuntu-client:/var/lib/apt/lists# 

oot@ubuntu-client:/var/lib/apt/lists# grep -w aide aa
aide is good
this is aide one
that is aide-common good
aide-good is not ok
hello aide-help
root@ubuntu-client
Run Code Online (Sandbox Code Playgroud)

ste*_*ver 5

您遇到的问题是-被视为非单词字符,因此aide其中的字符串aide-被视为单词。从man grep

  -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.  This option has no effect if -x is also specified.
Run Code Online (Sandbox Code Playgroud)

目前尚不清楚您的实际要求是什么,但是如果您想匹配前面或后面没有任何非空白字符的字符串,您可以切换到 grep 的 PCRE 模式并执行类似的操作

$ cat aa
aide is good
this is aide one
that is aide-common good
aide-good is not ok
hello aide-help

$ grep -P '(?<!\S)aide(?!\S)' aa
aide is good
this is aide one
Run Code Online (Sandbox Code Playgroud)

但请注意,这也必然会排除其他尾随标点符号,例如aide,aide.。要仅匹配aide前面或后面没有单词字符或连字符的地方,您可以使用

grep -P '(?<!(\w|-))aide(?!(\w|-))' aa
Run Code Online (Sandbox Code Playgroud)

作为参考,请参阅Lookahead 和 Lookbehind 零长度断言