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, "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
50 struct arg_list *regex;
53 static void do_grep(int fd, char *name)
55 FILE *file = fdopen(fd, "r");
57 int lcount = 0, mcount = 0, which = toys.optflags & FLAG_w ? 2 : 0;
58 char indelim = '\n' * !(toys.optflags&FLAG_z),
59 outdelim = '\n' * !(toys.optflags&FLAG_Z);
61 if (!fd) name = "(standard input)";
64 perror_msg("%s", name);
69 char *line = 0, *start;
70 regmatch_t matches[3];
76 if (0 > (len = getdelim(&line, &unused, indelim, file))) break;
77 if (line[len-1] == indelim) line[len-1] = 0;
85 if (toys.optflags & FLAG_F) {
86 struct arg_list *seek, fseek;
89 for (seek = TT.e; seek; seek = seek->next) {
90 if (toys.optflags & FLAG_x) {
91 int i = (toys.optflags & FLAG_i);
93 if ((i ? strcasecmp : strcmp)(seek->arg, line)) s = line;
94 } else if (!*seek->arg) {
99 if (toys.optflags & FLAG_i) {
100 long ll = strlen(seek->arg);;
102 // Alas, posix hasn't got strcasestr()
103 for (s = line; *s; s++) if (!strncasecmp(s, seek->arg, ll)) break;
105 } else s = strstr(line, seek->arg);
110 matches[which].rm_so = (s-line);
111 skip = matches[which].rm_eo = (s-line)+strlen(seek->arg);
114 rc = regexec((regex_t *)toybuf, start, 3, matches,
115 start==line ? 0 : REG_NOTBOL);
116 skip = matches[which].rm_eo;
119 if (toys.optflags & FLAG_x)
120 if (matches[which].rm_so || line[matches[which].rm_eo]) rc = 1;
122 if (toys.optflags & FLAG_v) {
123 if (toys.optflags & FLAG_o) {
124 if (rc) skip = matches[which].rm_eo = strlen(start);
125 else if (!matches[which].rm_so) {
128 } else matches[which].rm_eo = matches[which].rm_so;
131 matches[which].rm_eo = strlen(start);
133 matches[which].rm_so = 0;
134 } else if (rc) break;
138 if (toys.optflags & FLAG_q) xexit();
139 if (toys.optflags & FLAG_l) {
140 printf("%s%c", name, outdelim);
145 if (toys.optflags & FLAG_o)
146 if (matches[which].rm_eo == matches[which].rm_so)
149 if (!(toys.optflags & FLAG_c)) {
150 if (toys.optflags & FLAG_H) printf("%s:", name);
151 if (toys.optflags & FLAG_n) printf("%d:", lcount);
152 if (toys.optflags & FLAG_b)
153 printf("%ld:", offset + (start-line) +
154 ((toys.optflags & FLAG_o) ? matches[which].rm_so : 0));
155 if (!(toys.optflags & FLAG_o)) xprintf("%s%c", line, outdelim);
157 xprintf("%.*s%c", matches[which].rm_eo - matches[which].rm_so,
158 start + matches[which].rm_so, outdelim);
163 if (!(toys.optflags & FLAG_o) || !*start) break;
169 if (mmatch) mcount++;
170 if ((toys.optflags & FLAG_m) && mcount >= TT.m) break;
173 if (toys.optflags & FLAG_c) {
174 if (toys.optflags & FLAG_H) printf("%s:", name);
175 xprintf("%d%c", mcount, outdelim);
178 // loopfiles will also close the fd, but this frees an (opaque) struct.
182 static void parse_regex(void)
184 struct arg_list *al, *new, *list = NULL;
188 // Add all -f lines to -e list. (Yes, this is leaking allocation context for
189 // exit to free. Not supporting nofork for this command any time soon.)
190 al = TT.f ? TT.f : TT.e;
192 if (TT.f) s = ss = xreadfile(al->arg, 0, 0);
193 else s = ss = al->arg;
196 ss = strchr(s, '\n');
198 new = xmalloc(sizeof(struct arg_list));
212 if (!(toys.optflags & FLAG_F)) {
213 int w = toys.optflags & FLAG_w;
216 // Convert strings to one big regex
218 for (al = TT.e; al; al = al->next)
219 len += strlen(al->arg)+1+!(toys.optflags & FLAG_E);
221 regstr = s = xmalloc(len);
222 if (w) s = stpcpy(s, "(^|[^_[:alnum:]])(");
223 for (al = TT.e; al; al = al->next) {
224 s = stpcpy(s, al->arg);
225 if (!(toys.optflags & FLAG_E)) *(s++) = '\\';
228 *(s-=(1+!(toys.optflags & FLAG_E))) = 0;
229 if (w) strcpy(s, ")($|[^_[:alnum:]])");
231 w = regcomp((regex_t *)toybuf, regstr,
232 ((toys.optflags & FLAG_E) ? REG_EXTENDED : 0) |
233 ((toys.optflags & FLAG_i) ? REG_ICASE : 0));
236 regerror(w, (regex_t *)toybuf, toybuf+sizeof(regex_t),
237 sizeof(toybuf)-sizeof(regex_t));
238 error_exit("bad REGEX: %s", toybuf);
243 static int do_grep_r(struct dirtree *new)
247 if (new->parent && !dirtree_notdotdot(new)) return 0;
248 if (S_ISDIR(new->st.st_mode)) return DIRTREE_RECURSE;
250 // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
251 if (new->parent && !(toys.optflags & FLAG_h)) toys.optflags |= FLAG_H;
253 name = dirtree_path(new, 0);
254 do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
264 // Handle egrep and fgrep
265 if (*toys.which->name == 'e' || (toys.optflags & FLAG_w))
266 toys.optflags |= FLAG_E;
267 if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
269 if (!TT.e && !TT.f) {
270 if (!*toys.optargs) error_exit("no REGEX");
271 TT.e = xzalloc(sizeof(struct arg_list));
272 TT.e->arg = *(toys.optargs++);
278 if (!(toys.optflags & FLAG_h) && toys.optc>1) toys.optflags |= FLAG_H;
281 if (toys.optflags & FLAG_s) {
283 xopen("/dev/null", O_RDWR);
286 if (toys.optflags & FLAG_r) {
287 for (ss=toys.optargs; *ss; ss++) {
288 if (!strcmp(*ss, "-")) do_grep(0, *ss);
289 else dirtree_read(*ss, do_grep_r);
291 } else loopfiles_rw(toys.optargs, O_RDONLY, 0, 1, do_grep);