CodeBlue
CodeBlue

Reputation: 15389

How to grep to include an optional word?

I use the following grep query to find the occurrences of functions in a VB source file.

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

This matches -

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

   

However, it misses out on functions like -

   Private Static Sub SaveCustomer()

because of the additional word "Static" in there. How to account for this "optional" word in the grep query?

Upvotes: 22

Views: 36656

Answers (2)

Skippy Fastol
Skippy Fastol

Reputation: 1775

When using grep, cardinality wise:

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

Given the following example (where the very word stands for your 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

If we only want

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

we'll use the '?' (also notice the careful placement of the space after 'very ' to mention that we'll want the 'very' word zero or one time:

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

As you guessed it, I am inviting you to use egrep instead of grep (you can try grep -E, for Extended Regular Expressions).

Upvotes: 12

FatalError
FatalError

Reputation: 54561

You can use a \? to make something optional:

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

In this case, the preceding group, which contains the string "static", is optional (i.e. may occur 0 or 1 times).

Upvotes: 29

Related Questions