如何grep包含一个可选单词?

时间:2012-04-13 14:03:47

标签: grep

我使用以下grep查询来查找VB源文件中函数的出现次数。

    grep -nri "^\s*\(public\|private\|protected\)\s*\(sub\|function\)" formName.frm

匹配 -

    Private Sub Form_Unload(Cancel As Integer)
    Private Sub lbSelect_Click()
    ...

然而,它错过了像

这样的功能
   Private Static Sub SaveCustomer()

因为那里附加了“静态”字样。如何在grep查询中考虑这个“可选”字?

2 个答案:

答案 0 :(得分:16)

您可以使用\?制作可选内容:

grep -nri "^\s*\(public\|private\|protected\)\s*\(static\)\?\s*\(sub\|function\)" formName.frm

在这种情况下,前面的组包含字符串" static",是可选的(即可能出现0或1次)。

答案 1 :(得分:6)

使用grep时,基数明智:

* : 0 or many
+ : 1 or many
? : 0 or 1 <--- this is what you need.

给出以下示例(非常字代表静态):

I am well
I was well
You are well
You were well
I am very well
He is well
He was well
She is well
She was well
She was very well

如果我们只想要

I am well
I was well
You are well
You were well
I am very well

我们会用'?' (还要注意在“非常”之后仔细放置空格,提到我们要求'非常'一词为零或一次:

egrep "(I|You) (am|was|are|were) (very )?well" file.txt

正如您猜测的那样,我邀请您使用 egrep 而不是 grep (您可以尝试 grep -E ,用于扩展常规表达式)。