我想在文件中搜索特定的字符串并仅显示与该字符串完全匹配的行,但这似乎不起作用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
答案1
您遇到的问题是被视为非单词字符,因此中的-
字符串被视为单词。来自: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.
目前还不清楚你的实际要求是什么,但是如果你想匹配一个前面或后面没有任何非空白字符,你可以切换到 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
但请注意,这必然也会排除其他尾随标点符号,如aide,
和aide.
。仅匹配aide
前面或后面没有单词字符或连字符,你可以使用
grep -P '(?<!(\w|-))aide(?!(\w|-))' aa
如需参考,请参阅前瞻和后瞻零长度断言