Some cosmetic updates. Changed "OPTIONS" to "Options".
[oweals/busybox.git] / findutils / grep.c
1 /*
2  * Mini grep implementation for busybox using libc regex.
3  *
4  * Copyright (C) 1999,2000 by Lineo, inc.
5  * Written by Mark Whitley <markw@lineo.com>, <markw@enol.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  *
21  */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h> /* for getopt() */
26 #include <regex.h>
27 #include <string.h> /* for strerror() */
28 #include <errno.h>
29 #include "internal.h"
30
31 extern int optind; /* in unistd.h */
32 extern int errno;  /* for use with strerror() */
33
34 static const char grep_usage[] =
35         "grep [-ihHnqvs] pattern [files...]\n"
36 #ifndef BB_FEATURE_TRIVIAL_HELP
37         "\nSearch for PATTERN in each FILE or standard input.\n\n"
38         "Options:\n"
39         "\t-H\tprefix output lines with filename where match was found\n"
40         "\t-h\tsuppress the prefixing filename on output\n"
41         "\t-i\tignore case distinctions\n"
42         "\t-n\tprint line number with output lines\n"
43         "\t-q\tbe quiet. Returns 0 if result was found, 1 otherwise\n"
44         "\t-v\tselect non-matching lines\n"
45         "\t-s\tsuppress file open/read error messages\n\n"
46 #endif
47         ;
48
49 /* options */
50 static int ignore_case       = 0;
51 static int print_filename    = 0;
52 static int print_line_num    = 0;
53 static int be_quiet          = 0;
54 static int invert_search     = 0;
55 static int suppress_err_msgs = 0;
56
57 /* globals */
58 static regex_t regex; /* storage space for compiled regular expression */
59 static int nmatches = 0; /* keeps track of the number of matches */
60 static char *cur_file = NULL; /* the current file we are reading */
61
62
63 static void print_matched_line(char *line, int linenum)
64 {
65         if (print_filename)
66                 printf("%s:", cur_file);
67         if (print_line_num)
68                 printf("%i:", linenum);
69
70         printf("%s", line);
71 }
72
73 static void grep_file(FILE *file)
74 {
75         char *line = NULL;
76         int ret;
77         int linenum = 0;
78
79         while ((line = get_line_from_file(file)) != NULL) {
80                 linenum++;
81                 ret = regexec(&regex, line, 0, NULL, 0);
82                 if (ret == 0 && !invert_search) { /* match */
83
84                         /* if we found a match but were told to be quiet, stop here and
85                          * return success */
86                         if (be_quiet) {
87                                 regfree(&regex);
88                                 exit(0);
89                         }
90
91                         nmatches++;
92
93                         print_matched_line(line, linenum);
94
95                 } else if (ret == REG_NOMATCH && invert_search) {
96                         print_matched_line(line, linenum);
97                 }
98
99                 free(line);
100         }
101 }
102
103 extern int grep_main(int argc, char **argv)
104 {
105         int opt;
106         int reflags;
107         int ret;
108
109         /* do special-case option parsing */
110         if (argv[1] && (strcmp(argv[1], "--help") == 0))
111                 usage(grep_usage);
112
113         /* do normal option parsing */
114         while ((opt = getopt(argc, argv, "iHhnqvs")) > 0) {
115                 switch (opt) {
116                         case 'i':
117                                 ignore_case++;
118                                 break;
119                         case 'H':
120                                 print_filename++;
121                                 break;
122                         case 'h':
123                                 print_filename--;
124                                 break;
125                         case 'n':
126                                 print_line_num++;
127                                 break;
128                         case 'q':
129                                 be_quiet++;
130                                 break;
131                         case 'v':
132                                 invert_search++;
133                                 break;
134                         case 's':
135                                 suppress_err_msgs++;
136                                 break;
137                 }
138         }
139
140         /* argv[optind] should be the regex pattern; no pattern, no worky */
141         if (argv[optind] == NULL)
142                 usage(grep_usage);
143
144         /* compile the regular expression */
145         reflags = REG_NOSUB; /* we're not going to mess with sub-expressions */
146         if (ignore_case)
147                 reflags |= REG_ICASE;
148         if ((ret = regcomp(&regex, argv[optind], reflags)) != 0) {
149                 int errmsgsz = regerror(ret, &regex, NULL, 0);
150                 char *errmsg = malloc(errmsgsz);
151                 if (errmsg == NULL) {
152                         fprintf(stderr, "grep: memory error\n");
153                         regfree(&regex);
154                         exit(1);
155                 }
156                 regerror(ret, &regex, errmsg, errmsgsz);
157                 fprintf(stderr, "grep: %s\n", errmsg);
158                 free(errmsg);
159                 regfree(&regex);
160                 exit(1);
161         }
162
163         /* argv[(optind+1)..(argc-1)] should be names of file to grep through. If
164          * there is more than one file to grep, we will print the filenames */
165         if ((argc-1) - (optind+1) > 0)
166                 print_filename++;
167
168         /* If no files were specified, or '-' was specified, take input from
169          * stdin. Otherwise, we grep through all the files specified. */
170         if (argv[optind+1] == NULL || (strcmp(argv[optind+1], "-") == 0)) {
171                 grep_file(stdin);
172         } else {
173                 int i;
174                 FILE *file;
175                 for (i = optind + 1; i < argc; i++) {
176                         cur_file = argv[i];
177                         file = fopen(cur_file, "r");
178                         if (file == NULL) {
179                                 if (!suppress_err_msgs)
180                                         fprintf(stderr, "grep: %s: %s\n", cur_file, strerror(errno));
181                         } else {
182                                 grep_file(file);
183                                 fclose(file);
184                         }
185                 }
186         }
187
188         regfree(&regex);
189
190         if (nmatches == 0)
191                 return 1;
192
193         return 0;
194 }