While answering another question, I quoted man grep, in relation to -x

-x, --line-regexp
       Select only those matches that exactly match the whole line.
       For a regular expression pattern, this is like parenthesizing
       the pattern and then surrounding it with ^ and $.

I already knew that -x was like "surrounding [the regex] with ^ and $", but why does it also imply "parenthesizing the pattern"?

I can't think of why parenthesizing would be necessary, or even change anything. If the whole pattern were parenthesized, you couldn't refer to it internally with a capturing group. grep complains about trailing backslashes, so there's no odd behaviour from an appended ) either (nor would I expect that to be in the spirit of an option).

Why does man grep specifically mention parenthesizing the pattern for -x?

1 Answer 1


One instance where it’s important is for regular expressions with alternatives:

grep -E 'this|that'

If you only add ^ and $ without parenthesizing, this becomes

grep -E '^this|that$'

which matches lines starting with “this” or ending with “that”, rather than lines containing only “this” or “that”.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .