This matches the behavior of GNU grep.
---
 tests/grep.test   | 2 ++
 toys/posix/grep.c | 5 ++---
 2 files changed, 4 insertions(+), 3 deletions(-)
From 9935bd63d8350e4859914c1d566a99a4bc3acde4 Mon Sep 17 00:00:00 2001
From: Peter Collingbourne <p...@google.com>
Date: Tue, 21 Sep 2021 11:18:22 -0700
Subject: [PATCH] grep: Make --color highlight all matches on a line.

This matches the behavior of GNU grep.
---
 tests/grep.test   | 2 ++
 toys/posix/grep.c | 5 ++---
 2 files changed, 4 insertions(+), 3 deletions(-)

diff --git a/tests/grep.test b/tests/grep.test
index 215491c2..45db0842 100755
--- a/tests/grep.test
+++ b/tests/grep.test
@@ -202,3 +202,5 @@ testing "-z with \n in pattern" "grep -f input" "hi\nthere\n" "i\nt" "hi\nthere"
 
 testing "print zero length match" "grep '[0-9]*'" "abc\n" "" "abc\n"
 testing "-o skip zero length match" "grep -o '[0-9]*'" "1234\n" "" "a1234b"
+
+testing "--color" "grep --color=always l" "\033[0mhe\033[1;31ml\033[0m\033[1;31ml\033[0mo\n" "" "hello\n"
diff --git a/toys/posix/grep.c b/toys/posix/grep.c
index 8eb3c03a..8d8d63eb 100644
--- a/toys/posix/grep.c
+++ b/toys/posix/grep.c
@@ -296,9 +296,9 @@ static void do_grep(int fd, char *name)
             outline(FLAG(color) ? 0 : line, ':', name, lcount, bcount, ulen);
           if (FLAG(color)) {
             xputsn(TT.grey);
-            if (mm->rm_so) xputsl(line, mm->rm_so);
+            if (mm->rm_so) xputsl(start, mm->rm_so);
             xputsn(TT.red);
-            xputsl(line+mm->rm_so, mm->rm_eo-mm->rm_so);
+            xputsl(start+mm->rm_so, mm->rm_eo-mm->rm_so);
           }
 
           if (TT.A) after = TT.A+1;
@@ -307,7 +307,6 @@ static void do_grep(int fd, char *name)
 
       start += mm->rm_eo;
       if (mm->rm_so == mm->rm_eo) break;
-      if (!FLAG(o) && FLAG(color)) break;
     } while (*start);
     offset += len;
 
-- 
2.33.0.464.g1972c5931b-goog

_______________________________________________
Toybox mailing list
Toybox@lists.landley.net
http://lists.landley.net/listinfo.cgi/toybox-landley.net

Reply via email to