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_EGREP(OLDTOY(egrep, grep, TOYFLAG_BIN))
9 USE_FGREP(OLDTOY(fgrep, 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
60 struct arg_list *regex;
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 char indelim = '\n' * !(toys.optflags&FLAG_z),
69 outdelim = '\n' * !(toys.optflags&FLAG_Z);
71 if (!fd) name = "(standard input)";
74 perror_msg("%s", name);
79 char *line = 0, *start;
80 regmatch_t matches[3];
86 if (0 > (len = getdelim(&line, &unused, indelim, file))) break;
87 if (line[len-1] == indelim) line[len-1] = 0;
95 if (toys.optflags & FLAG_F) {
96 struct arg_list *seek, fseek;
99 for (seek = TT.e; seek; seek = seek->next) {
100 if (toys.optflags & FLAG_x) {
101 int i = (toys.optflags & FLAG_i);
103 if ((i ? strcasecmp : strcmp)(seek->arg, line)) s = line;
104 } else if (!*seek->arg) {
106 fseek.arg = s = line;
109 if (toys.optflags & FLAG_i) {
110 long ll = strlen(seek->arg);;
112 // Alas, posix hasn't got strcasestr()
113 for (s = line; *s; s++) if (!strncasecmp(s, seek->arg, ll)) break;
115 } else s = strstr(line, seek->arg);
120 matches[which].rm_so = (s-line);
121 skip = matches[which].rm_eo = (s-line)+strlen(seek->arg);
124 rc = regexec((regex_t *)toybuf, start, 3, matches,
125 start==line ? 0 : REG_NOTBOL);
126 skip = matches[which].rm_eo;
129 if (toys.optflags & FLAG_x)
130 if (matches[which].rm_so || line[matches[which].rm_eo]) rc = 1;
132 if (toys.optflags & FLAG_v) {
133 if (toys.optflags & FLAG_o) {
134 if (rc) skip = matches[which].rm_eo = strlen(start);
135 else if (!matches[which].rm_so) {
138 } else matches[which].rm_eo = matches[which].rm_so;
141 matches[which].rm_eo = strlen(start);
143 matches[which].rm_so = 0;
144 } else if (rc) break;
148 if (toys.optflags & FLAG_q) xexit();
149 if (toys.optflags & FLAG_l) {
150 printf("%s%c", name, outdelim);
155 if (toys.optflags & FLAG_o)
156 if (matches[which].rm_eo == matches[which].rm_so)
159 if (!(toys.optflags & FLAG_c)) {
160 if (toys.optflags & FLAG_H) printf("%s:", name);
161 if (toys.optflags & FLAG_n) printf("%d:", lcount);
162 if (toys.optflags & FLAG_b)
163 printf("%ld:", offset + (start-line) +
164 ((toys.optflags & FLAG_o) ? matches[which].rm_so : 0));
165 if (!(toys.optflags & FLAG_o)) xprintf("%s%c", line, outdelim);
167 xprintf("%.*s%c", matches[which].rm_eo - matches[which].rm_so,
168 start + matches[which].rm_so, outdelim);
173 if (!(toys.optflags & FLAG_o) || !*start) break;
179 if (mmatch) mcount++;
180 if ((toys.optflags & FLAG_m) && mcount >= TT.m) break;
183 if (toys.optflags & FLAG_c) {
184 if (toys.optflags & FLAG_H) printf("%s:", name);
185 xprintf("%d%c", mcount, outdelim);
188 // loopfiles will also close the fd, but this frees an (opaque) struct.
192 static void parse_regex(void)
194 struct arg_list *al, *new, *list = NULL;
198 // Add all -f lines to -e list. (Yes, this is leaking allocation context for
199 // exit to free. Not supporting nofork for this command any time soon.)
200 al = TT.f ? TT.f : TT.e;
202 if (TT.f) s = ss = xreadfile(al->arg, 0, 0);
203 else s = ss = al->arg;
206 ss = strchr(s, '\n');
208 new = xmalloc(sizeof(struct arg_list));
222 if (!(toys.optflags & FLAG_F)) {
223 int w = toys.optflags & FLAG_w;
226 // Convert strings to one big regex
228 for (al = TT.e; al; al = al->next)
229 len += strlen(al->arg)+1+!(toys.optflags & FLAG_E);
231 regstr = s = xmalloc(len);
232 if (w) s = stpcpy(s, "(^|[^_[:alnum:]])(");
233 for (al = TT.e; al; al = al->next) {
234 s = stpcpy(s, al->arg);
235 if (!(toys.optflags & FLAG_E)) *(s++) = '\\';
238 *(s-=(1+!(toys.optflags & FLAG_E))) = 0;
239 if (w) strcpy(s, ")($|[^_[:alnum:]])");
241 w = regcomp((regex_t *)toybuf, regstr,
242 ((toys.optflags & FLAG_E) ? REG_EXTENDED : 0) |
243 ((toys.optflags & FLAG_i) ? REG_ICASE : 0));
246 regerror(w, (regex_t *)toybuf, toybuf+sizeof(regex_t),
247 sizeof(toybuf)-sizeof(regex_t));
248 error_exit("bad REGEX: %s", toybuf);
253 static int do_grep_r(struct dirtree *new)
257 if (new->parent && !dirtree_notdotdot(new)) return 0;
258 if (S_ISDIR(new->st.st_mode)) return DIRTREE_RECURSE;
260 // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
261 if (new->parent && !(toys.optflags & FLAG_h)) toys.optflags |= FLAG_H;
263 name = dirtree_path(new, 0);
264 do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
272 char **ss = toys.optargs;
274 // Handle egrep and fgrep
275 if (*toys.which->name == 'e' || (toys.optflags & FLAG_w))
276 toys.optflags |= FLAG_E;
277 if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
279 if (!TT.e && !TT.f) {
280 if (!*ss) error_exit("no REGEX");
281 TT.e = xzalloc(sizeof(struct arg_list));
288 if (!(toys.optflags & FLAG_h) && toys.optc>1) toys.optflags |= FLAG_H;
291 if (toys.optflags & FLAG_s) {
293 xopen("/dev/null", O_RDWR);
296 if (toys.optflags & FLAG_r) {
297 for (ss = *ss ? ss : (char *[]){".", 0}; *ss; ss++) {
298 if (!strcmp(*ss, "-")) do_grep(0, *ss);
299 else dirtree_read(*ss, do_grep_r);
301 } else loopfiles_rw(toys.optargs, O_RDONLY, 0, 1, do_grep);