diff options
-rw-r--r-- | findutils/grep.c | 10 | ||||
-rwxr-xr-x | testsuite/grep.tests | 4 |
2 files changed, 11 insertions, 3 deletions
diff --git a/findutils/grep.c b/findutils/grep.c index 688ea6ab2..024f27609 100644 --- a/findutils/grep.c +++ b/findutils/grep.c | |||
@@ -461,15 +461,19 @@ static int grep_file(FILE *file) | |||
461 | if (found) | 461 | if (found) |
462 | print_line(gl->pattern, strlen(gl->pattern), linenum, ':'); | 462 | print_line(gl->pattern, strlen(gl->pattern), linenum, ':'); |
463 | } else while (1) { | 463 | } else while (1) { |
464 | unsigned start = gl->matched_range.rm_so; | ||
464 | unsigned end = gl->matched_range.rm_eo; | 465 | unsigned end = gl->matched_range.rm_eo; |
466 | unsigned len = end - start; | ||
465 | char old = line[end]; | 467 | char old = line[end]; |
466 | line[end] = '\0'; | 468 | line[end] = '\0'; |
467 | print_line(line + gl->matched_range.rm_so, | 469 | /* Empty match is not printed: try "echo test | grep -o ''" */ |
468 | end - gl->matched_range.rm_so, | 470 | if (len != 0) |
469 | linenum, ':'); | 471 | print_line(line + start, len, linenum, ':'); |
470 | if (old == '\0') | 472 | if (old == '\0') |
471 | break; | 473 | break; |
472 | line[end] = old; | 474 | line[end] = old; |
475 | if (len == 0) | ||
476 | end++; | ||
473 | #if !ENABLE_EXTRA_COMPAT | 477 | #if !ENABLE_EXTRA_COMPAT |
474 | if (regexec(&gl->compiled_regex, line + end, | 478 | if (regexec(&gl->compiled_regex, line + end, |
475 | 1, &gl->matched_range, REG_NOTBOL) != 0) | 479 | 1, &gl->matched_range, REG_NOTBOL) != 0) |
diff --git a/testsuite/grep.tests b/testsuite/grep.tests index 520a1840f..ffce033e6 100755 --- a/testsuite/grep.tests +++ b/testsuite/grep.tests | |||
@@ -98,5 +98,9 @@ testing "grep -o does not loop forever" \ | |||
98 | 'grep -o "[^/]*$"' \ | 98 | 'grep -o "[^/]*$"' \ |
99 | "test\n" \ | 99 | "test\n" \ |
100 | "" "/var/test\n" | 100 | "" "/var/test\n" |
101 | testing "grep -o does not loop forever on zero-length match" \ | ||
102 | 'grep -o "" | head -n1' \ | ||
103 | "" \ | ||
104 | "" "test\n" | ||
101 | 105 | ||
102 | exit $FAILCOUNT | 106 | exit $FAILCOUNT |