1 /* $OpenBSD: grep.c,v 1.45 2012/12/29 01:32:44 millert Exp $ */
4 * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/types.h>
31 #include <sys/limits.h>
36 #include <sys/queue.h>
50 /* Flags passed to regcomp() and regexec() */
52 int eflags
= REG_STARTEND
;
54 int matchall
; /* shortcut */
55 int patterns
, pattern_sz
;
58 fastgrep_t
*fg_pattern
;
60 /* For regex errors */
61 char re_error
[RE_ERROR_BUF
+ 1];
63 /* Command-line flags */
64 int Aflag
; /* -A x: print x lines trailing each match */
65 int Bflag
; /* -B x: print x lines leading each match */
66 int Eflag
; /* -E: interpret pattern as extended regexp */
67 int Fflag
; /* -F: interpret pattern as list of fixed strings */
68 int Gflag
; /* -G: interpret pattern as basic regexp */
69 int Hflag
; /* -H: always print filename header */
70 int Lflag
; /* -L: only show names of files with no matches */
71 int Rflag
; /* -R: recursively search directory trees */
73 int Zflag
; /* -Z: decompress input before processing */
75 int bflag
; /* -b: show block numbers for each match */
76 int cflag
; /* -c: only show a count of matching lines */
77 int hflag
; /* -h: don't print filename headers */
78 int iflag
; /* -i: ignore case */
79 int lflag
; /* -l: only show names of files with matches */
80 int nflag
; /* -n: show line numbers in front of matching lines */
81 int oflag
; /* -o: print each match */
82 int qflag
; /* -q: quiet mode (don't output anything) */
83 int sflag
; /* -s: silent mode (ignore errors) */
84 int vflag
; /* -v: only show non-matching lines */
85 int wflag
; /* -w: pattern must start and end on word boundaries */
86 int xflag
; /* -x: pattern must match entire line */
87 int lbflag
; /* --line-buffered */
89 int binbehave
= BIN_FILE_BIN
;
92 BIN_OPT
= CHAR_MAX
+ 1,
99 int first
; /* flag whether or not this is our first match */
100 int tail
; /* lines left to print */
101 int file_err
; /* file reading error */
105 SLIST_ENTRY(patfile
) pf_next
;
107 SLIST_HEAD(, patfile
) patfilelh
;
109 extern char *__progname
;
116 "usage: %s [-abcEFGHhIiLlnoqRsUVvwx] [-A num] [-B num] [-C[num]]\n"
118 "usage: %s [-abcEFGHhIiLlnoqRsUVvwxZ] [-A num] [-B num] [-C[num]]\n"
120 "\t[-e pattern] [-f file] [--binary-files=value] [--context[=num]]\n"
121 "\t[--line-buffered] [pattern] [file ...]\n", __progname
);
126 static const char *optstr
= "0123456789A:B:CEFGHILRUVabce:f:hilnoqrsuvwxy";
128 static const char *optstr
= "0123456789A:B:CEFGHILRUVZabce:f:hilnoqrsuvwxy";
131 struct option long_options
[] =
133 {"binary-files", required_argument
, NULL
, BIN_OPT
},
134 {"help", no_argument
, NULL
, HELP_OPT
},
135 {"mmap", no_argument
, NULL
, MMAP_OPT
},
136 {"line-buffered", no_argument
, NULL
, LINEBUF_OPT
},
137 {"after-context", required_argument
, NULL
, 'A'},
138 {"before-context", required_argument
, NULL
, 'B'},
139 {"context", optional_argument
, NULL
, 'C'},
140 {"devices", required_argument
, NULL
, 'D'},
141 {"extended-regexp", no_argument
, NULL
, 'E'},
142 {"fixed-strings", no_argument
, NULL
, 'F'},
143 {"basic-regexp", no_argument
, NULL
, 'G'},
144 {"with-filename", no_argument
, NULL
, 'H'},
145 {"binary", no_argument
, NULL
, 'U'},
146 {"version", no_argument
, NULL
, 'V'},
147 {"text", no_argument
, NULL
, 'a'},
148 {"byte-offset", no_argument
, NULL
, 'b'},
149 {"count", no_argument
, NULL
, 'c'},
150 {"regexp", required_argument
, NULL
, 'e'},
151 {"file", required_argument
, NULL
, 'f'},
152 {"no-filename", no_argument
, NULL
, 'h'},
153 {"ignore-case", no_argument
, NULL
, 'i'},
154 {"files-without-match", no_argument
, NULL
, 'L'},
155 {"files-with-matches", no_argument
, NULL
, 'l'},
156 {"line-number", no_argument
, NULL
, 'n'},
157 {"quiet", no_argument
, NULL
, 'q'},
158 {"silent", no_argument
, NULL
, 'q'},
159 {"recursive", no_argument
, NULL
, 'r'},
160 {"no-messages", no_argument
, NULL
, 's'},
161 {"revert-match", no_argument
, NULL
, 'v'},
162 {"word-regexp", no_argument
, NULL
, 'w'},
163 {"line-regexp", no_argument
, NULL
, 'x'},
164 {"unix-byte-offsets", no_argument
, NULL
, 'u'},
166 {"decompress", no_argument
, NULL
, 'Z'},
168 {NULL
, no_argument
, NULL
, 0}
173 add_pattern(char *pat
, size_t len
)
175 if (!xflag
&& (len
== 0 || matchall
)) {
179 if (patterns
== pattern_sz
) {
181 pattern
= grep_realloc(pattern
, ++pattern_sz
* sizeof(*pattern
));
183 if (len
> 0 && pat
[len
- 1] == '\n')
185 /* pat may not be NUL-terminated */
186 if (wflag
&& !Fflag
) {
187 int bol
= 0, eol
= 0, extra
;
190 if (len
> 0 && pat
[len
- 1] == '$')
192 extra
= Eflag
? 2 : 4;
193 pattern
[patterns
] = grep_malloc(len
+ 15 + extra
);
194 snprintf(pattern
[patterns
], len
+ 15 + extra
,
195 "%s[[:<:]]%s%.*s%s[[:>:]]%s",
198 (int)len
- bol
- eol
, pat
+ bol
,
203 pattern
[patterns
] = grep_malloc(len
+ 1);
204 memcpy(pattern
[patterns
], pat
, len
);
205 pattern
[patterns
][len
] = '\0';
211 add_patterns(char *pats
)
215 while ((nl
= strchr(pats
, '\n')) != NULL
) {
216 add_pattern(pats
, nl
- pats
);
219 add_pattern(pats
, strlen(pats
));
223 read_patterns(const char *fn
)
229 if ((f
= fopen(fn
, "r")) == NULL
)
231 while ((line
= fgetln(f
, &len
)) != NULL
)
232 add_pattern(line
, *line
== '\n' ? 0 : len
);
239 main(int argc
, char *argv
[])
241 int c
, lastc
, prevoptind
, newarg
, i
, needpattern
, exprs
, expr_sz
;
242 struct patfile
*patfile
, *pf_next
;
246 SLIST_INIT(&patfilelh
);
247 switch (__progname
[0]) {
260 switch(__progname
[1]) {
281 while ((c
= getopt_long(argc
, argv
, optstr
,
282 long_options
, NULL
)) != -1) {
284 case '0': case '1': case '2': case '3': case '4':
285 case '5': case '6': case '7': case '8': case '9':
286 if (newarg
|| !isdigit(lastc
))
288 else if (Aflag
> INT_MAX
/ 10)
289 errx(2, "context out of range");
290 Aflag
= Bflag
= (Aflag
* 10) + (c
- '0');
294 l
= strtol(optarg
, &ep
, 10);
295 if (ep
== optarg
|| *ep
!= '\0' ||
296 l
<= 0 || l
>= INT_MAX
)
297 errx(2, "context out of range");
307 l
= strtol(optarg
, &ep
, 10);
308 if (ep
== optarg
|| *ep
!= '\0' ||
309 l
<= 0 || l
>= INT_MAX
)
310 errx(2, "context out of range");
311 Aflag
= Bflag
= (int)l
;
330 binbehave
= BIN_FILE_SKIP
;
341 binbehave
= BIN_FILE_BIN
;
344 fprintf(stderr
, "grep version %u.%u\n", VER_MAJ
, VER_MIN
);
353 binbehave
= BIN_FILE_TEXT
;
362 /* defer adding of expressions until all arguments are parsed */
363 if (exprs
== expr_sz
) {
365 expr
= grep_realloc(expr
, ++expr_sz
* sizeof(*expr
));
368 expr
[exprs
] = optarg
;
372 patfile
= grep_malloc(sizeof(*patfile
));
373 patfile
->pf_file
= optarg
;
374 SLIST_INSERT_HEAD(&patfilelh
, patfile
, pf_next
);
411 if (strcmp("binary", optarg
) == 0)
412 binbehave
= BIN_FILE_BIN
;
413 else if (strcmp("without-match", optarg
) == 0)
414 binbehave
= BIN_FILE_SKIP
;
415 else if (strcmp("text", optarg
) == 0)
416 binbehave
= BIN_FILE_TEXT
;
418 errx(2, "Unknown binary-files option");
422 /* default, compatibility */
432 newarg
= optind
!= prevoptind
;
438 for (i
= 0; i
< exprs
; i
++)
439 add_patterns(expr
[i
]);
443 for (patfile
= SLIST_FIRST(&patfilelh
); patfile
!= NULL
;
445 pf_next
= SLIST_NEXT(patfile
, pf_next
);
446 read_patterns(patfile
->pf_file
);
450 if (argc
== 0 && needpattern
)
453 if (argc
!= 0 && needpattern
) {
460 cflags
|= REG_EXTENDED
;
462 cflags
|= REG_NOSPEC
;
464 /* Sorry, this won't work */
466 errx(1, "Can't use small fgrep with -w");
468 fg_pattern
= grep_calloc(patterns
, sizeof(*fg_pattern
));
469 r_pattern
= grep_calloc(patterns
, sizeof(*r_pattern
));
470 for (i
= 0; i
< patterns
; ++i
) {
471 /* Check if cheating is allowed (always is for fgrep). */
474 fgrepcomp(&fg_pattern
[i
], (unsigned char *)pattern
[i
]);
478 if (fastcomp(&fg_pattern
[i
], pattern
[i
])) {
479 /* Fall back to full regex library */
480 c
= regcomp(&r_pattern
[i
], pattern
[i
], cflags
);
482 regerror(c
, &r_pattern
[i
], re_error
,
484 errx(2, "%s", re_error
);
493 if ((argc
== 0 || argc
== 1) && !Rflag
&& !Hflag
)
497 exit(!procfile(NULL
));
502 for (c
= 0; argc
--; ++argv
)
503 c
+= procfile(*argv
);
505 exit(c
? (file_err
? (qflag
? 0 : 2) : 0) : (file_err
? 2 : 1));