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
9 USE_GREP(NEWTOY(grep, "ZzEFHabhinorsvwclqe*f*m#x[!wx][!EFw]", TOYFLAG_BIN))
10 USE_EGREP(OLDTOY(egrep, grep, TOYFLAG_BIN))
11 USE_FGREP(OLDTOY(fgrep, grep, TOYFLAG_BIN))
17 usage: grep [-EFivwcloqsHbhn] [-m MAX] [-e REGEX]... [-f REGFILE] [FILE]...
19 Show lines matching regular expressions. If no -e, first argument is
20 regular expression to match. With no files (or "-" filename) read stdin.
21 Returns 0 if matched, 1 if no match found.
23 -e Regex to match. (May be repeated.)
24 -f File containing regular expressions to match.
27 -E extended regex syntax -F fixed (match literal string)
28 -i case insensitive -m stop after this many lines matched
29 -r recursive (on dir) -v invert match
30 -w whole word (implies -E) -x whole line
31 -z input NUL terminated
33 display modes: (default: matched line)
34 -c count of matching lines -l show matching filenames
35 -o only matching part -q quiet (errors only)
36 -s silent (no error msg) -Z output NUL terminated
38 output prefix (default: filename if checking more than 1 file)
39 -H force filename -b byte offset of match
40 -h hide filename -n line number of match
63 // Show matches in one file
64 static void do_grep(int fd, char *name)
66 FILE *file = fdopen(fd, "r");
68 int lcount = 0, mcount = 0;
69 char indelim = '\n' * !(toys.optflags&FLAG_z),
70 outdelim = '\n' * !(toys.optflags&FLAG_Z);
72 if (!fd) name = "(standard input)";
79 // Loop through lines of input
81 char *line = 0, *start;
88 if (0 > (len = getdelim(&line, &unused, indelim, file))) break;
89 if (line[len-1] == indelim) line[len-1] = 0;
93 // Loop through matches in this line
97 // Handle non-regex matches
98 if (toys.optflags & FLAG_F) {
99 struct arg_list *seek, fseek;
102 for (seek = TT.e; seek; seek = seek->next) {
103 if (toys.optflags & FLAG_x) {
104 int i = (toys.optflags & FLAG_i);
106 if ((i ? strcasecmp : strcmp)(seek->arg, line)) s = line;
107 } else if (!*seek->arg) {
109 fseek.arg = s = line;
112 if (toys.optflags & FLAG_i) {
113 long ll = strlen(seek->arg);;
115 // Alas, posix hasn't got strcasestr()
116 for (s = line; *s; s++) if (!strncasecmp(s, seek->arg, ll)) break;
118 } else s = strstr(line, seek->arg);
123 matches.rm_so = (s-line);
124 skip = matches.rm_eo = (s-line)+strlen(seek->arg);
127 rc = regexec((regex_t *)toybuf, start, 1, &matches,
128 start==line ? 0 : REG_NOTBOL);
129 skip = matches.rm_eo;
132 if (toys.optflags & FLAG_x)
133 if (matches.rm_so || line[matches.rm_eo]) rc = 1;
135 if (!rc && (toys.optflags & FLAG_w)) {
138 if ((start+matches.rm_so)!=line) {
139 c = start[matches.rm_so-1];
140 if (!isalnum(c) && c != '_') c = 0;
143 c = start[matches.rm_eo];
144 if (!isalnum(c) && c != '_') c = 0;
147 start += matches.rm_so+1;
153 if (toys.optflags & FLAG_v) {
154 if (toys.optflags & FLAG_o) {
155 if (rc) skip = matches.rm_eo = strlen(start);
156 else if (!matches.rm_so) {
159 } else matches.rm_eo = matches.rm_so;
162 matches.rm_eo = strlen(start);
165 } else if (rc) break;
169 if (toys.optflags & FLAG_q) xexit();
170 if (toys.optflags & FLAG_l) {
171 printf("%s%c", name, outdelim);
176 if (toys.optflags & FLAG_o)
177 if (matches.rm_eo == matches.rm_so)
180 if (!(toys.optflags & FLAG_c)) {
181 if (toys.optflags & FLAG_H) printf("%s:", name);
182 if (toys.optflags & FLAG_n) printf("%d:", lcount);
183 if (toys.optflags & FLAG_b)
184 printf("%ld:", offset + (start-line) +
185 ((toys.optflags & FLAG_o) ? matches.rm_so : 0));
186 if (!(toys.optflags & FLAG_o)) xprintf("%s%c", line, outdelim);
188 xprintf("%.*s%c", matches.rm_eo - matches.rm_so,
189 start + matches.rm_so, outdelim);
194 if (!(toys.optflags & FLAG_o)) break;
200 if (mmatch) mcount++;
201 if ((toys.optflags & FLAG_m) && mcount >= TT.m) break;
204 if (toys.optflags & FLAG_c) {
205 if (toys.optflags & FLAG_H) printf("%s:", name);
206 xprintf("%d%c", mcount, outdelim);
209 // loopfiles will also close the fd, but this frees an (opaque) struct.
213 static void parse_regex(void)
215 struct arg_list *al, *new, *list = NULL;
219 // Add all -f lines to -e list. (Yes, this is leaking allocation context for
220 // exit to free. Not supporting nofork for this command any time soon.)
221 al = TT.f ? TT.f : TT.e;
223 if (TT.f) s = ss = xreadfile(al->arg, 0, 0);
224 else s = ss = al->arg;
226 // Split lines at \n, add individual lines to new list.
228 ss = strchr(s, '\n');
230 new = xmalloc(sizeof(struct arg_list));
237 // Advance, when we run out of -f switch to -e.
246 if (!(toys.optflags & FLAG_F)) {
250 // Convert strings to one big regex
251 for (al = TT.e; al; al = al->next)
252 len += strlen(al->arg)+1+!(toys.optflags & FLAG_E);
254 regstr = s = xmalloc(len);
255 for (al = TT.e; al; al = al->next) {
256 s = stpcpy(s, al->arg);
257 if (!(toys.optflags & FLAG_E)) *(s++) = '\\';
260 *(s-=(1+!(toys.optflags & FLAG_E))) = 0;
262 i = regcomp((regex_t *)toybuf, regstr,
263 ((toys.optflags & FLAG_E) ? REG_EXTENDED : 0) |
264 ((toys.optflags & FLAG_i) ? REG_ICASE : 0));
267 regerror(i, (regex_t *)toybuf, toybuf+sizeof(regex_t),
268 sizeof(toybuf)-sizeof(regex_t));
269 error_exit("bad REGEX: %s", toybuf);
274 static int do_grep_r(struct dirtree *new)
278 if (new->parent && !dirtree_notdotdot(new)) return 0;
279 if (S_ISDIR(new->st.st_mode)) return DIRTREE_RECURSE;
281 // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
282 if (new->parent && !(toys.optflags & FLAG_h)) toys.optflags |= FLAG_H;
284 name = dirtree_path(new, 0);
285 do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
293 char **ss = toys.optargs;
295 // Handle egrep and fgrep
296 if (*toys.which->name == 'e') toys.optflags |= FLAG_E;
297 if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
299 if (!TT.e && !TT.f) {
300 if (!*ss) error_exit("no REGEX");
301 TT.e = xzalloc(sizeof(struct arg_list));
308 if (!(toys.optflags & FLAG_h) && toys.optc>1) toys.optflags |= FLAG_H;
311 if (toys.optflags & FLAG_s) {
313 xopen("/dev/null", O_RDWR);
316 if (toys.optflags & FLAG_r) {
317 // Iterate through -r arguments. Use "." as default if none provided.
318 for (ss = *ss ? ss : (char *[]){".", 0}; *ss; ss++) {
319 if (!strcmp(*ss, "-")) do_grep(0, *ss);
320 else dirtree_read(*ss, do_grep_r);
322 } else loopfiles_rw(ss, O_RDONLY, 0, 1, do_grep);