@matheusbsbs / matheus-bagliano / commits / c41dd2fd7d
Fork 0

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>

René Scharfe committed Mar 19, 2011 at 19:33 UTC c41dd2fd7d3a16e6f0b1629d688bee3240db496c
2 files changed +9 -2
builtin/grep.c
+4 -2
@@ -659,11 +659,12 @@ static int context_callback(const struct option *opt, const char *arg,
659 static int file_callback(const struct option *opt, const char *arg, int unset)
660 {
661 struct grep_opt *grep_opt = opt->value;
662 + int from_stdin = !strcmp(arg, "-");
663 FILE *patterns;
664 int lno = 0;
665 struct strbuf sb = STRBUF_INIT;
666
666 - patterns = fopen(arg, "r");
667 + patterns = from_stdin ? stdin : fopen(arg, "r");
668 if (!patterns)
669 die_errno("cannot open '%s'", arg);
670 while (strbuf_getline(&sb, patterns, '\n') == 0) {
@@ -677,7 +678,8 @@ static int file_callback(const struct option *opt, const char *arg, int unset)
678 s = strbuf_detach(&sb, &len);
679 append_grep_pat(grep_opt, s, len, arg, ++lno, GREP_PATTERN);
680 }
680 - fclose(patterns);
681 + if (!from_stdin)
682 + fclose(patterns);
683 strbuf_release(&sb);
684 return 0;
685 }
t/t7810-grep.sh
+5
@@ -303,6 +303,11 @@ test_expect_success 'grep -f, ignore empty lines' '
303 test_cmp expected actual
304 '
305
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 +
311 cat >expected <<EOF
312 y:y yy
313 --