grep: fix --column --only-match for 2nd and later matches

"git grep --column --only-match" shows the 1-based column number of the first match on each line, but confusing numbers for further matches. Example: $ echo 123456789012345678901234567890 >file $ for d in 1 2 3 4 5 6 7 8 9 0 do git grep --no-index --column --only-matching $d file | awk -v FS=: -v l=$d: '{l = l sprintf("%3s", $2)} END {print l}' done 1: 1 2 12 2: 2 4 14 3: 3 6 16 4: 4 8 18 5: 5 10 20 6: 6 12 22 7: 7 14 24 8: 8 16 26 9: 9 18 28 0: 10 20 30 Report the column number of each match instead: $ for d in 1 2 3 4 5 6 7 8 9 0 do ./git grep --no-index --column --only-matching $d file | awk -v FS=: -v l=$d: '{l = l sprintf("%3s", $2)} END {print l}' done 1: 1 11 21 2: 2 12 22 3: 3 13 23 4: 4 14 24 5: 5 15 25 6: 6 16 26 7: 7 17 27 8: 8 18 28 9: 9 19 29 0: 10 20 30 We need to adjust the test in t7810 as well. The file it uses has the following five lines; I add a line highlighting the matches and a ruler at the bottom here, to make it easier to see that the second "mmap" indeed starts at column 14: foo mmap bar foo_mmap bar foo_mmap bar mmap foo mmap bar_mmap foo_mmap bar mmap baz ==== ==== 123456789 123456789 1 Reported-by: Brandon Chinn <brandonchinn178@gmail.com> Signed-off-by: René Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

René Scharfe committed Apr 24, 2026 at 23:04 UTC 9ff4b5ab1b3b66d454a6c09e92d608c9be15a7a9
2 files changed +5 -4
grep.c
+2 -1
@@ -1267,6 +1267,7 @@ static void show_line(struct grep_opt *opt,
1267 regmatch_t match;
1268 enum grep_context ctx = GREP_CONTEXT_BODY;
1269 int eflags = 0;
1270 + const char *start = bol;
1271
1272 if (want_color(opt->color)) {
1273 if (sign == ':')
@@ -1285,6 +1286,7 @@ static void show_line(struct grep_opt *opt,
1286 if (match.rm_so == match.rm_eo)
1287 break;
1288
1289 + cno = bol - start + match.rm_so + 1;
1290 if (opt->only_matching)
1291 show_line_header(opt, name, lno, cno, sign);
1292 else
@@ -1294,7 +1296,6 @@ static void show_line(struct grep_opt *opt,
1296 if (opt->only_matching)
1297 opt->output(opt, "\n", 1);
1298 bol += match.rm_eo;
1297 - cno += match.rm_eo;
1299 rest -= match.rm_eo;
1300 eflags = REG_NOTBOL;
1301 }
t/t7810-grep.sh
+3 -3
@@ -322,11 +322,11 @@ do
322 ${HC}file:1:5:mmap
323 ${HC}file:2:5:mmap
324 ${HC}file:3:5:mmap
325 - ${HC}file:3:13:mmap
325 + ${HC}file:3:14:mmap
326 ${HC}file:4:5:mmap
327 - ${HC}file:4:13:mmap
327 + ${HC}file:4:14:mmap
328 ${HC}file:5:5:mmap
329 - ${HC}file:5:13:mmap
329 + ${HC}file:5:14:mmap
330 EOF
331 git grep --column -n -o -e mmap $H >actual &&
332 test_cmp expected actual