4 char *validflags = "bchiLlnsv";
8 fprint(2, "usage: grep [-%s] [-e pattern] [-f patternfile] [file ...]\n", validflags);
13 main(int argc, char *argv[])
19 if(utfrune(validflags, ARGC()) == nil)
27 str2top(EARGF(usage()));
32 filename = EARGF(usage());
33 rein = Bopen(filename, OREAD);
35 fprint(2, "grep: can't open %s: %r\n", filename);
43 if(flags['f'] == 0 && flags['e'] == 0) {
51 follow = mal(maxfollow*sizeof(*follow));
52 state0 = initstate(topre.beg);
54 Binit(&bout, 1, OWRITE);
57 status = search(0, 0);
60 status = search(argv[0], 0);
65 status |= search(argv[i], Hflag);
74 search(char *file, int flag)
77 int c, fid, eof, nl, empty;
78 long count, lineno, n;
79 uchar *elp, *lp, *bol;
86 fid = open(file, OREAD);
89 fprint(2, "grep: can't open %s: %r\n", file);
94 flag ^= Bflag; /* dont buffer output */
96 flag |= Cflag; /* count */
98 flag &= ~Hflag; /* do not print file name in output */
100 flag |= Iflag; /* fold upper-lower */
102 flag |= Llflag; /* print only name of file if any match */
104 flag |= LLflag; /* print only name of file if any non match */
106 flag |= Nflag; /* count only */
108 flag |= Sflag; /* status only */
110 flag |= Vflag; /* inverse match */
123 if(n > sizeof(u.pre))
125 memmove(u.buf-n, bol, n);
127 n = read(fid, u.buf, sizeof(u.buf));
128 /* if file has no final newline, simulate one to emit matches to last line */
131 nl = u.buf[n-1]=='\n';
134 fprint(2, "grep: read error on %s: %r\n", file);
137 if(!eof && !nl && !empty) {
147 Bprint(&bout, "%s:", file);
148 Bprint(&bout, "%ld\n", count);
150 if(((flag&Llflag) && count != 0) || ((flag&LLflag) && count == 0))
151 Bprint(&bout, "%s\n", file);
161 * normal character loop
172 // print("%d: %.2x**\n", s, c);
174 // print("%d: %.2x\n", s, c);
179 if(!!s->match == !(flag&Vflag)) {
181 if(flag & (Cflag|Sflag|Llflag|LLflag))
184 Bprint(&bout, "%s:", file);
186 Bprint(&bout, "%ld: ", lineno);
187 /* suppress extra newline at EOF unless we are labeling matches with file name */
188 Bwrite(&bout, bol, lp-bol-(eof && !(flag&Hflag)));
192 if((lineno & Flshcnt) == 0)
202 * character loop for -i flag
207 if(c >= 'A' && c <= 'Z')
218 if(!!s->match == !(flag&Vflag)) {
220 if(flag & (Cflag|Sflag|Llflag|LLflag))
223 Bprint(&bout, "%s:", file);
225 Bprint(&bout, "%ld: ", lineno);
226 /* suppress extra newline at EOF unless we are labeling matches with file name */
227 Bwrite(&bout, bol, lp-bol-(eof && !(flag&Hflag)));
231 if((lineno & Flshcnt) == 0)
253 follow[nfollow++] = r;
254 qsort(follow, nfollow, sizeof(*follow), fcmp);
257 for(i=0; i<nfollow; i++)
258 s->re[i] = follow[i];