c0nt0s0
c0nt0s0

Reputation: 151

How to include optional space in Grep statement

I have some log files that I'm grepping through which contain entries in the following form

foo($abc) - sometext
foo ($xyz) - moretext
baz($qux) - moartext

I'm looking to use grep that would output the first two lines as matches, i.e.

foo($abc)
foo ($xyz)

I've tried the following grep statement

grep 'foo(\$' log.txt

which outputs the first match, but I tried to include an optional space, and neither return:

grep 'foo\s?(\$' log.txt

I'm using the optional space incorrectly, but I'm unsure how

Upvotes: 4

Views: 1674

Answers (2)

Arkadiusz Drabczyk
Arkadiusz Drabczyk

Reputation: 12403

You can either change the query slightly and use * instead of ?:

grep 'foo *(\$' log.txt

or use a literal whitespace and escape ?:

grep 'foo \?(\$' log.txt

Both solutions would work with GNU, busybox and FreeBSD grep.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

You are using a POSIX BRE regex and foo\s?(\$ matches foo, a whitespace, a literal ?, a literal ( and a literal $.

You can use

grep -E 'foo\s?\(\$' log.txt

Here, -E makes the pattern POSIX ERE, and thus it now matches foo, then an optional whitespace, and a ($ substring.

See an online demo:

s='foo($abc) - sometext
foo ($xyz) - moretext
baz($qux) - moartext'
grep -E 'foo\s?\(\$' <<< "$s"

Output:

foo($abc) - sometext
foo ($xyz) - moretext

You may still use a more universal syntax like

grep 'foo[[:space:]]\{0,1\}(\$' log.txt

It is a POSIX BRE regex matching foo, one or zero whitespaces, and then ($ substring.

Upvotes: 3

Related Questions