1 /* vi: set sw=4 ts=4: */
3 * Mini grep implementation for busybox using libc regex.
5 * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
6 * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org>
8 * Licensed under the GPL v2, see the file LICENSE in this tarball.
10 /* BB_AUDIT SUSv3 defects - unsupported option -x. */
11 /* BB_AUDIT GNU defects - always acts as -a. */
12 /* http://www.opengroup.org/onlinepubs/007904975/utilities/grep.html */
14 * Apr 2004 by Vladimir Oleynik <dzo@simtreas.ru> -
15 * correction "-e pattern1 -e pattern2" logic and more optimizations.
28 static unsigned long opt;
29 #define GREP_OPTS "lnqvscFiHhe:f:L"
30 #define GREP_OPT_l (1<<0)
31 #define PRINT_FILES_WITH_MATCHES (opt & GREP_OPT_l)
32 #define GREP_OPT_n (1<<1)
33 #define PRINT_LINE_NUM (opt & GREP_OPT_n)
34 #define GREP_OPT_q (1<<2)
35 #define BE_QUIET (opt & GREP_OPT_q)
36 #define GREP_OPT_v (1<<3)
37 typedef char invert_search_t;
38 static invert_search_t invert_search;
39 #define GREP_OPT_s (1<<4)
40 #define SUPPRESS_ERR_MSGS (opt & GREP_OPT_s)
41 #define GREP_OPT_c (1<<5)
42 #define PRINT_MATCH_COUNTS (opt & GREP_OPT_c)
43 #define GREP_OPT_F (1<<6)
44 #define FGREP_FLAG (opt & GREP_OPT_F)
45 #define GREP_OPT_i (1<<7)
46 #define GREP_OPT_H (1<<8)
47 #define GREP_OPT_h (1<<9)
48 #define GREP_OPT_e (1<<10)
49 #define GREP_OPT_f (1<<11)
50 #define GREP_OPT_L (1<<12)
51 #define PRINT_FILES_WITHOUT_MATCHES ((opt & GREP_OPT_L) != 0)
52 #if ENABLE_FEATURE_GREP_CONTEXT
53 #define GREP_OPT_CONTEXT "A:B:C"
54 #define GREP_OPT_A (1<<13)
55 #define GREP_OPT_B (1<<14)
56 #define GREP_OPT_C (1<<15)
57 #define GREP_OPT_E (1<<16)
59 #define GREP_OPT_CONTEXT ""
60 #define GREP_OPT_A (0)
61 #define GREP_OPT_B (0)
62 #define GREP_OPT_C (0)
63 #define GREP_OPT_E (1<<13)
65 #if ENABLE_FEATURE_GREP_EGREP_ALIAS
66 # define OPT_EGREP "E"
72 static int print_filename;
74 #if ENABLE_FEATURE_GREP_CONTEXT
75 static int lines_before;
76 static int lines_after;
77 static char **before_buf;
78 static int last_line_printed;
79 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
81 /* globals used internally */
82 static llist_t *pattern_head; /* growable list of patterns to match */
83 static char *cur_file; /* the current file we are reading */
86 static void print_line(const char *line, int linenum, char decoration)
88 #if ENABLE_FEATURE_GREP_CONTEXT
89 /* possibly print the little '--' separator */
90 if ((lines_before || lines_after) && last_line_printed &&
91 last_line_printed < linenum - 1) {
94 last_line_printed = linenum;
96 if (print_filename > 0)
97 printf("%s%c", cur_file, decoration);
99 printf("%i%c", linenum, decoration);
104 static int grep_file(FILE *file)
110 #if ENABLE_FEATURE_GREP_CONTEXT
111 int print_n_lines_after = 0;
112 int curpos = 0; /* track where we are in the circular 'before' buffer */
113 int idx = 0; /* used for iteration through the circular buffer */
114 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
116 while ((line = bb_get_chomped_line_from_file(file)) != NULL) {
117 llist_t *pattern_ptr = pattern_head;
121 while (pattern_ptr) {
123 ret = strstr(line, pattern_ptr->data) != NULL;
126 * test for a postitive-assertion match (regexec returns success (0)
127 * and the user did not specify invert search), or a negative-assertion
128 * match (regexec returns failure (REG_NOMATCH) and the user specified
132 xregcomp(®ex, pattern_ptr->data, reflags);
133 ret |= regexec(®ex, line, 0, NULL, 0) == 0;
136 pattern_ptr = pattern_ptr->link;
137 } /* while (pattern_ptr) */
139 if ((ret ^ invert_search)) {
141 if (PRINT_FILES_WITH_MATCHES || BE_QUIET)
144 /* if we found a match but were told to be quiet, stop here */
145 if (BE_QUIET || PRINT_FILES_WITHOUT_MATCHES)
148 /* keep track of matches */
151 /* if we're just printing filenames, we stop after the first match */
152 if (PRINT_FILES_WITH_MATCHES)
155 /* print the matched line */
156 if (PRINT_MATCH_COUNTS == 0) {
157 #if ENABLE_FEATURE_GREP_CONTEXT
158 int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
160 /* if we were told to print 'before' lines and there is at least
161 * one line in the circular buffer, print them */
162 if (lines_before && before_buf[prevpos] != NULL) {
163 int first_buf_entry_line_num = linenum - lines_before;
165 /* advance to the first entry in the circular buffer, and
166 * figure out the line number is of the first line in the
169 while (before_buf[idx] == NULL) {
170 idx = (idx + 1) % lines_before;
171 first_buf_entry_line_num++;
174 /* now print each line in the buffer, clearing them as we go */
175 while (before_buf[idx] != NULL) {
176 print_line(before_buf[idx], first_buf_entry_line_num, '-');
177 free(before_buf[idx]);
178 before_buf[idx] = NULL;
179 idx = (idx + 1) % lines_before;
180 first_buf_entry_line_num++;
184 /* make a note that we need to print 'after' lines */
185 print_n_lines_after = lines_after;
187 print_line(line, linenum, ':');
190 #if ENABLE_FEATURE_GREP_CONTEXT
191 else { /* no match */
192 /* Add the line to the circular 'before' buffer */
194 free(before_buf[curpos]);
195 before_buf[curpos] = bb_xstrdup(line);
196 curpos = (curpos + 1) % lines_before;
200 /* if we need to print some context lines after the last match, do so */
201 if (print_n_lines_after && (last_line_printed != linenum)) {
202 print_line(line, linenum, '-');
203 print_n_lines_after--;
205 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
210 /* special-case file post-processing for options where we don't print line
211 * matches, just filenames and possibly match counts */
213 /* grep -c: print [filename:]count, even if count is zero */
214 if (PRINT_MATCH_COUNTS) {
215 if (print_filename > 0)
216 printf("%s:", cur_file);
217 printf("%d\n", nmatches);
220 /* grep -l: print just the filename, but only if we grepped the line in the file */
221 if (PRINT_FILES_WITH_MATCHES && nmatches > 0) {
225 /* grep -L: print just the filename, but only if we didn't grep the line in the file */
226 if (PRINT_FILES_WITHOUT_MATCHES && nmatches == 0) {
233 static void load_regexes_from_file(llist_t *fopt)
240 char *ffile = cur->data;
244 f = bb_xfopen(ffile, "r");
245 while ((line = bb_get_chomped_line_from_file(f)) != NULL) {
246 pattern_head = llist_add_to(pattern_head, line);
252 extern int grep_main(int argc, char **argv)
256 llist_t *fopt = NULL;
257 int error_open_count = 0;
259 /* do normal option parsing */
260 #if ENABLE_FEATURE_GREP_CONTEXT
267 bb_opt_complementally = "H-h:e::f::C-AB";
268 opt = bb_getopt_ulflags(argc, argv,
269 GREP_OPTS GREP_OPT_CONTEXT OPT_EGREP,
270 &pattern_head, &fopt,
271 &slines_after, &slines_before, &Copt);
273 if(opt & GREP_OPT_C) {
274 /* C option unseted A and B options, but next -A or -B
275 may be ovewrite own option */
276 if(!(opt & GREP_OPT_A)) /* not overwtited */
278 if(!(opt & GREP_OPT_B)) /* not overwtited */
279 slines_before = Copt;
280 opt |= GREP_OPT_A|GREP_OPT_B; /* set for parse now */
282 if(opt & GREP_OPT_A) {
283 lines_after = strtoul(slines_after, &junk, 10);
285 bb_error_msg_and_die("invalid context length argument");
287 if(opt & GREP_OPT_B) {
288 lines_before = strtoul(slines_before, &junk, 10);
290 bb_error_msg_and_die("invalid context length argument");
292 /* sanity checks after parse may be invalid numbers ;-) */
293 if ((opt & (GREP_OPT_c|GREP_OPT_q|GREP_OPT_l|GREP_OPT_L))) {
297 } else if(lines_before > 0)
298 before_buf = (char **)xcalloc(lines_before, sizeof(char *));
301 /* with auto sanity checks */
302 bb_opt_complementally = "H-h:e::f::c-n:q-n:l-n";
303 opt = bb_getopt_ulflags(argc, argv, GREP_OPTS OPT_EGREP,
304 &pattern_head, &fopt);
306 invert_search = (opt & GREP_OPT_v) != 0; /* 0 | 1 */
313 load_regexes_from_file(fopt);
315 if(ENABLE_FEATURE_GREP_FGREP_ALIAS && bb_applet_name[0] == 'f')
318 if(ENABLE_FEATURE_GREP_EGREP_ALIAS &&
319 (bb_applet_name[0] == 'e' || (opt & GREP_OPT_E)))
320 reflags = REG_EXTENDED | REG_NOSUB;
325 reflags |= REG_ICASE;
330 /* if we didn't get a pattern from a -e and no command file was specified,
331 * argv[optind] should be the pattern. no pattern, no worky */
332 if (pattern_head == NULL) {
336 pattern_head = llist_add_to(pattern_head, *argv++);
341 /* argv[(optind)..(argc-1)] should be names of file to grep through. If
342 * there is more than one file to grep, we will print the filenames */
346 /* If no files were specified, or '-' was specified, take input from
347 * stdin. Otherwise, we grep through all the files specified. */
348 } else if (argc == 0) {
354 if(!cur_file || (*cur_file == '-' && !cur_file[1])) {
355 cur_file = "(standard input)";
358 file = fopen(cur_file, "r");
361 if (!SUPPRESS_ERR_MSGS)
362 bb_perror_msg("%s", cur_file);
365 matched += grep_file(file);
367 /* we found a match but were told to be quiet, stop here and
375 /* destroy all the elments in the pattern list */
376 if (ENABLE_FEATURE_CLEAN_UP)
377 while (pattern_head) {
378 llist_t *pattern_head_ptr = pattern_head;
380 pattern_head = pattern_head->link;
381 free(pattern_head_ptr);
384 /* 0 = success, 1 = failed, 2 = error */
385 /* If the -q option is specified, the exit status shall be zero
386 * if an input line is selected, even if an error was detected. */
387 if(BE_QUIET && matched)
391 return !matched; /* invert return value 0 = success, 1 = failed */