21

我使用以下 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 查询中解释这个“可选”词?

4

2 回答 2

25

您可以使用 a\?使某些内容成为可选:

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

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

于 2012-04-13T14:07:46.067 回答
10

使用 grep 时,基数明智:

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

给定以下示例(这个代表您的static):

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

我们将使用“?” (还要注意在“very”之后小心放置空格,以提及我们希望“very”这个词出现零次或一次:

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

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

于 2012-04-13T14:21:10.907 回答