Search code examples
grep

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


Solution

  • 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.