I read that grouping treats an expression as a single unit. What does that mean?
Furthermore, what does grep "\(grouping\)" file.txt
or grep -E "(grouping)" file.txt
do? I also read that expressions are grouped with parenthesis. Again, what is grouping expressions?
When I run the command, it highlights grouping
in the file. How is grep "\(grouping\)"
different from grep grouping
?
Essentially, it causes whatever is inside the parentheses to be treated as a single atom. This is useful if you want to apply a quantifier for example. Compare:
(where
*
is only applied to theg
) withwhere
*
is applied to the whole subpatterngrouping
.In most (all?) regex dialects,
(grouping)
also captures the matched text into an indexed capture group, allowing it to subsequently be backreferenced. That doesn't have too many applications ingrep
- the most obvious one is for detecting repeated elements ex.matches any single character that is followed by the same character. In the context of pattern substitution (in
sed
for example, rather thangrep
), the captured group may also be referenced in the replacement text.There are other variants in more expressive dialects - such as Perl's
(?:grouping)
non-capturing groups.For further information see for example