Skip to content

fix: grep context lines with several matches - #3289

Open
b84330808 wants to merge 1 commit into
alibaba:masterfrom
b84330808:fix-grep-context-lines
Open

b84330808 wants to merge 1 commit into
alibaba:masterfrom
b84330808:fix-grep-context-lines

Conversation

@b84330808

Copy link
Copy Markdown

grep -A/-B/-C works for a single match but goes wrong with several:

  • -B without -A: the leading context of a later match lands in front of the previous match. ABC,1,2,ABC,3 | grep -B1 ABC gives 2,ABC,ABC instead of ABC,2,ABC.
  • Leading context overlapping lines already printed prints them again.
  • Lines inside trailing context are never tested, so a match there gets no context of its own and isn't counted by -m. ABC,1,ABC,2,3 | grep -A1 ABC drops 2.
  • Context lines ignore --trim-end.

The loop now walks the lines once and remembers the last printed line. I checked the expected output in the new tests against GNU grep. Line number prefixes on context lines stay : as before.

The -A, -B and -C handling only worked for a single match:

- leading context of a later match was inserted in front of the previous
  match when there was no trailing context
- lines that were already printed were printed again when leading context
  overlapped them
- lines inside trailing context were never tested, so a match there got no
  context of its own and was not counted by -m
- context lines ignored --trim-end

Walk the lines once and remember the last printed line, like GNU grep.
@CLAassistant

CLAassistant commented Nov 6, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants