1 /* grep.c - print lines what match given regular expression
3 * Copyright 2013 CE Strake <strake888 at gmail.com>
5 * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html
7 USE_GREP(NEWTOY(grep, "A#B#C#ZzEFHabhinorsvwclqe*f*m#x[!wx][!EFw]", TOYFLAG_BIN))
8 USE_GREP(OLDTOY(egrep, grep, OPTSTR_grep, TOYFLAG_BIN))
9 USE_GREP(OLDTOY(fgrep, grep, OPTSTR_grep, TOYFLAG_BIN))
15 usage: grep [-EFivwcloqsHbhn] [-m MAX] [-e REGEX]... [-f REGFILE] [FILE]...
17 Show lines matching regular expressions. If no -e, first argument is
18 regular expression to match. With no files (or "-" filename) read stdin.
19 Returns 0 if matched, 1 if no match found.
21 -e Regex to match. (May be repeated.)
22 -f File containing regular expressions to match.
25 -E extended regex syntax -F fixed (match literal string)
26 -i case insensitive -m stop after this many lines matched
27 -r recursive (on dir) -v invert match
28 -w whole word (implies -E) -x whole line
29 -z input NUL terminated
31 display modes: (default: matched line)
32 -c count of matching lines -l show matching filenames
33 -o only matching part -q quiet (errors only)
34 -s silent (no error msg) -Z output NUL terminated
36 output prefix (default: filename if checking more than 1 file)
37 -H force filename -b byte offset of match
38 -h hide filename -n line number of match
53 struct arg_list *regex;
54 struct double_list *blist;
63 static void do_grep(int fd, char *name)
65 FILE *file = fdopen(fd, "r");
67 int lcount = 0, mcount = 0, which = toys.optflags & FLAG_w ? 2 : 0,
68 blines = 0, alines = 0, dash = 0;
69 char indelim = '\n' * !(toys.optflags&FLAG_z),
70 outdelim = '\n' * !(toys.optflags&FLAG_Z);
72 if (!fd) name = "(standard input)";
74 fprintf(stderr, "boo\n");
76 perror_msg("%s", name);
80 // Loop through lines of input
82 char *oline = 0, *line = 0, *start;
83 regmatch_t matches[3];
88 // Read next line of input
90 if (0 > (len = getdelim(&line, &unused, indelim, file))) break;
91 if (line[len-1] == indelim) line[len-1] = 0;
92 fprintf(stderr, "line=%s\n", line);
93 // Unconditionally add line to blist so output can always just dump blist.
94 dlist_add(&TT.blist, line);
95 fprintf(stderr, "added=%s\n", TT.blist->data);
96 fprintf(stderr, "prev=%s\n", TT.blist->prev->data);
97 if (blines <= TT.B) blines++;
99 struct double_list *temp = dlist_pop(&TT.blist);
100 fprintf(stderr, "bird=%s\n", temp->data);
107 // Loop to match multiple times within the same line (if necessary)
109 fprintf(stderr, "match?\n");
110 int rc = 0, skip = 0;
112 if (toys.optflags & FLAG_F) {
113 struct arg_list *seek, fseek;
116 for (seek = TT.e; seek; seek = seek->next) {
117 if (toys.optflags & FLAG_x) {
118 int i = (toys.optflags & FLAG_i);
120 if ((i ? strcasecmp : strcmp)(seek->arg, line)) s = line;
121 } else if (!*seek->arg) {
123 fseek.arg = s = line;
126 if (toys.optflags & FLAG_i) {
127 long ll = strlen(seek->arg);;
129 // Alas, posix hasn't got strcasestr()
130 for (s = line; *s; s++) if (!strncasecmp(s, seek->arg, ll)) break;
132 } else s = strstr(line, seek->arg);
137 matches[which].rm_so = (s-line);
138 skip = matches[which].rm_eo = (s-line)+strlen(seek->arg);
141 rc = regexec((regex_t *)toybuf, start, 3, matches,
142 start==line ? 0 : REG_NOTBOL);
143 skip = matches[which].rm_eo;
146 if (toys.optflags & FLAG_x)
147 if (matches[which].rm_so || line[matches[which].rm_eo]) rc = 1;
149 if (toys.optflags & FLAG_v) {
150 if (toys.optflags & FLAG_o) {
151 if (rc) skip = matches[which].rm_eo = strlen(start);
152 else if (!matches[which].rm_so) {
155 } else matches[which].rm_eo = matches[which].rm_so;
158 matches[which].rm_eo = strlen(start);
160 matches[which].rm_so = 0;
161 } else if (rc) break;
162 fprintf(stderr, "got match %s\n", line);
163 // We got a match, figure out how to display it
166 if (toys.optflags & FLAG_q) xexit();
167 if (toys.optflags & FLAG_l) {
168 printf("%s%c", name, outdelim);
173 fprintf(stderr, "here=%s\n", TT.blist->prev->data);
174 // Yes, -o sometimes counts things as a match (-c) but doesn't display it
175 if (toys.optflags & FLAG_o)
176 if (matches[which].rm_eo == matches[which].rm_so)
179 // List of lines that DIDN'T match, print backlog?
180 // Except this includes the one we just matched...?
182 struct double_list *dlist = dlist_pop(&TT.blist);
183 char *ll = dlist->data;
184 fprintf(stderr, "popped %s\n", ll);
185 if (dash) printf("--%c", outdelim);
188 if (!(toys.optflags & FLAG_c)) {
189 if (toys.optflags & FLAG_H) printf("%s:", name);
190 if (toys.optflags & FLAG_n) printf("%d:", lcount);
191 if (toys.optflags & FLAG_b)
192 printf("%ld:", offset + (start - dlist->data) +
193 ((toys.optflags & FLAG_o) ? matches[which].rm_so : 0));
194 if (!(toys.optflags & FLAG_o)) xprintf("%s%c", dlist->data, outdelim);
195 else if (!TT.blist) {
197 // TODO: FLAG_o prints multiple times, can't free it yet?
198 xprintf("%.*s%c", matches[which].rm_eo - matches[which].rm_so,
199 start + matches[which].rm_so, outdelim);
203 if (oline && !TT.blist) TT.blist = dlist;
211 if (!(toys.optflags & FLAG_o) || !*start) break;
214 fprintf(stderr, "Spacious skies\n");
217 if (mmatch) mcount++;
218 if ((toys.optflags & FLAG_m) && mcount >= TT.m) break;
221 if (toys.optflags & FLAG_c) {
222 if (toys.optflags & FLAG_H) printf("%s:", name);
223 xprintf("%d%c", mcount, outdelim);
227 while (CFG_TOYBOX_FREE && TT.blist) {
228 struct double_list *dlist = dlist_pop(&TT.blist);
234 // loopfiles will also close the fd, but this frees an (opaque) struct.
238 static void parse_regex(void)
240 struct arg_list *al, *new, *list = NULL;
244 // Add all -f lines to -e list. (Yes, this is leaking allocation context for
245 // exit to free. Not supporting nofork for this command any time soon.)
246 al = TT.f ? TT.f : TT.e;
248 if (TT.f) s = ss = xreadfile(al->arg, 0, 0);
249 else s = ss = al->arg;
252 ss = strchr(s, '\n');
254 new = xmalloc(sizeof(struct arg_list));
268 if (!(toys.optflags & FLAG_F)) {
269 int w = toys.optflags & FLAG_w;
272 // Convert strings to one big regex
274 for (al = TT.e; al; al = al->next)
275 len += strlen(al->arg)+1+!(toys.optflags & FLAG_E);
277 regstr = s = xmalloc(len);
278 if (w) s = stpcpy(s, "(^|[^_[:alnum:]])(");
279 for (al = TT.e; al; al = al->next) {
280 s = stpcpy(s, al->arg);
281 if (!(toys.optflags & FLAG_E)) *(s++) = '\\';
284 *(s-=(1+!(toys.optflags & FLAG_E))) = 0;
285 if (w) strcpy(s, ")($|[^_[:alnum:]])");
287 w = regcomp((regex_t *)toybuf, regstr,
288 ((toys.optflags & FLAG_E) ? REG_EXTENDED : 0) |
289 ((toys.optflags & FLAG_i) ? REG_ICASE : 0));
292 regerror(w, (regex_t *)toybuf, toybuf+sizeof(regex_t),
293 sizeof(toybuf)-sizeof(regex_t));
294 error_exit("bad REGEX: %s", toybuf);
299 static int do_grep_r(struct dirtree *new)
303 if (new->parent && !dirtree_notdotdot(new)) return 0;
304 if (S_ISDIR(new->st.st_mode)) return DIRTREE_RECURSE;
306 // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
307 if (new->parent && !(toys.optflags & FLAG_h)) toys.optflags |= FLAG_H;
309 name = dirtree_path(new, 0);
310 do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
320 // Handle egrep and fgrep
321 if (*toys.which->name == 'e' || (toys.optflags & FLAG_w))
322 toys.optflags |= FLAG_E;
323 if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
325 if (!TT.e && !TT.f) {
326 if (!*toys.optargs) error_exit("no REGEX");
327 TT.e = xzalloc(sizeof(struct arg_list));
328 TT.e->arg = *(toys.optargs++);
332 if (!TT.A) TT.A = TT.C;
333 if (!TT.B) TT.B = TT.C;
334 if (toys.optflags & (FLAG_l|FLAG_o)) TT.B = 0; // avoid memory leak
338 if (!(toys.optflags & FLAG_h) && toys.optc>1) toys.optflags |= FLAG_H;
341 if (toys.optflags & FLAG_s) {
343 xopen("/dev/null", O_RDWR);
346 if (toys.optflags & FLAG_r) {
347 for (ss=toys.optargs; *ss; ss++) {
348 if (!strcmp(*ss, "-")) do_grep(0, *ss);
349 else dirtree_read(*ss, do_grep_r);
351 } else loopfiles_rw(toys.optargs, O_RDONLY, 0, 1, do_grep);