Skip to content

Commit c41dd2f

Browse files
René Scharfegitster
authored andcommitted
grep: read patterns from stdin with -f -
Support the well-know convention of reading standard input instead of a named file if "-" (dash) is specified. GNU grep does the same. Signed-off-by: Rene Scharfe <rene.scharfe@lsrfire.ath.cx> Signed-off-by: Junio C Hamano <gitster@pobox.com>
1 parent af4c62a commit c41dd2f

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

builtin/grep.c

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -659,11 +659,12 @@ static int context_callback(const struct option *opt, const char *arg,
659659
static int file_callback(const struct option *opt, const char *arg, int unset)
660660
{
661661
struct grep_opt *grep_opt = opt->value;
662+
int from_stdin = !strcmp(arg, "-");
662663
FILE *patterns;
663664
int lno = 0;
664665
struct strbuf sb = STRBUF_INIT;
665666

666-
patterns = fopen(arg, "r");
667+
patterns = from_stdin ? stdin : fopen(arg, "r");
667668
if (!patterns)
668669
die_errno("cannot open '%s'", arg);
669670
while (strbuf_getline(&sb, patterns, '\n') == 0) {
@@ -677,7 +678,8 @@ static int file_callback(const struct option *opt, const char *arg, int unset)
677678
s = strbuf_detach(&sb, &len);
678679
append_grep_pat(grep_opt, s, len, arg, ++lno, GREP_PATTERN);
679680
}
680-
fclose(patterns);
681+
if (!from_stdin)
682+
fclose(patterns);
681683
strbuf_release(&sb);
682684
return 0;
683685
}

t/t7810-grep.sh

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,11 @@ test_expect_success 'grep -f, ignore empty lines' '
303303
test_cmp expected actual
304304
'
305305

306+
test_expect_success 'grep -f, ignore empty lines, read patterns from stdin' '
307+
git grep -f - <patterns >actual &&
308+
test_cmp expected actual
309+
'
310+
306311
cat >expected <<EOF
307312
y:y yy
308313
--

0 commit comments

Comments
 (0)