Context Line Control (GNU Grep 3.7)

From Get docs
Grep/docs/latest/Context-Line-Control /
Revision as of 03:31, 6 December 2021 by Notes (talk | contribs) (Page commit)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

2.1.5 Context Line Control

Context lines are non-matching lines that are near a matching line. They are output only if one of the following options are used. Regardless of how these options are set, grep never outputs any given line more than once. If the -o (--only-matching) option is specified, these options have no effect and a warning is given upon their use.

-A num
--after-context=num

Print num lines of trailing context after matching lines.

-B num
--before-context=num

Print num lines of leading context before matching lines.

-C num
-num
--context=num

Print num lines of leading and trailing output context.

--group-separator=string

When -A, -B or -C are in use, print string instead of -- between groups of lines.

--no-group-separator

When -A, -B or -C are in use, do not print a separator between groups of lines.

Here are some points about how grep chooses the separator to print between prefix fields and line content:

  • Matching lines normally use ‘:’ as a separator between prefix fields and actual line content.
  • Context (i.e., non-matching) lines use ‘-’ instead.
  • When context is not specified, matching lines are simply output one right after another.
  • When context is specified, lines that are adjacent in the input form a group and are output one right after another, while by default a separator appears between non-adjacent groups.
  • The default separator is a ‘--’ line; its presence and appearance can be changed with the options above.
  • Each group may contain several matching lines when they are close enough to each other that two adjacent groups connect and can merge into a single contiguous one.