Grep 正则表达式以任意顺序查找单词
上下文:我想在很多源代码文件中找到一个类定义,但我不知道确切的名称。
问题:我知道一些单词必须出现在我想要查找的行上,但我不知道它们出现的顺序。有没有一种快速的方法可以在同一行上以任意顺序查找多个单词?
Context: I want to find a class definition within a lot of source code files, but I do not know the exact name.
Question: I know a number of words which must appear on the line I want to find, but I do not know the order in which they will appear. Is there a quick way to look for a number of words in any order on the same line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于需要搜索大量单词的情况,可以使用 awk,如下所示:(
如果您是 cygwin 用户,则命令为
gawk
。)For situations where you need to search on a large number of words, you can use awk as follows:
(If you are a cygwin user, the command is
gawk
.)如果您想查找 foo、bar 和 baz,您可以这样做:
这将找到以任意顺序包含这三个元素的任何内容。如果使用egrep,则可以使用单词边界,否则将匹配子字符串。
If you're trying to find foo, bar, and baz, you can just do:
That will find anything that has all three in any order. You can use word boundaries if you use egrep, otherwise that will match substrings.
虽然这不是您的 grep 问题的确切答案,但您应该检查“ctags”命令以从源代码生成标签文件。对于源代码对象,这应该比简单的 grep 对您有更多帮助。检查:http://ctags.sourceforge.net/ctags.html
While this is not an exact answer your grep question, but you should check the "ctags" command for generating tags file from the source code. For the source code objects this should help you a much more than an simple grep. check: http://ctags.sourceforge.net/ctags.html
使用标准基本正则表达式从当前目录开始递归匹配任何带有指定单词的
.c
文件(不区分大小写,bash 风格):使用标准扩展正则表达式:
您还可以使用正则表达式:
Using standard basic regex recursively match starting from the current directory any
.c
file with the indicated words (case insesitive, bash flavour):Using standard extended regex:
You can also use perl regex:
如果您需要使用单个 grep 命令进行搜索(例如,您正在标准输入上搜索多个模式替代方案),您可以使用:
这将找到包含 word1 和 word2 任意顺序,或 替代词。
(请注意,随着任意顺序的单词数量增加,此方法会变得指数级复杂。)
If you need to search with a single grep command (for example, you are searching for multiple pattern alternatives on stdin), you could use:
This would find anything which has word1 and word2 in either order, or alternative-word.
(Note that this method gets exponentially complicated as the number of words in arbitrary order increases.)