1 /* $OpenBSD: grep.c,v 1.38 2007/02/13 21:48:20 kili 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/queue.h>
45 /* Flags passed to regcomp() and regexec() */
47 int eflags
= REG_STARTEND
;
49 int matchall
; /* shortcut */
50 int patterns
, pattern_sz
;
53 fastgrep_t
*fg_pattern
;
55 /* For regex errors */
56 char re_error
[RE_ERROR_BUF
+ 1];
58 /* Command-line flags */
59 int Aflag
; /* -A x: print x lines trailing each match */
60 int Bflag
; /* -B x: print x lines leading each match */
61 int Eflag
; /* -E: interpret pattern as extended regexp */
62 int Fflag
; /* -F: interpret pattern as list of fixed strings */
63 int Gflag
; /* -G: interpret pattern as basic regexp */
64 int Hflag
; /* -H: if -R, follow explicitly listed symlinks */
65 int Lflag
; /* -L: only show names of files with no matches */
66 int Pflag
; /* -P: if -R, no symlinks are followed */
67 int Rflag
; /* -R: recursively search directory trees */
68 int Sflag
; /* -S: if -R, follow all symlinks */
70 int Zflag
; /* -Z: decompress input before processing */
72 int bflag
; /* -b: show block numbers for each match */
73 int cflag
; /* -c: only show a count of matching lines */
74 int hflag
; /* -h: don't print filename headers */
75 int iflag
; /* -i: ignore case */
76 int lflag
; /* -l: only show names of files with matches */
77 int nflag
; /* -n: show line numbers in front of matching lines */
78 int oflag
; /* -o: always print file name */
79 int qflag
; /* -q: quiet mode (don't output anything) */
80 int sflag
; /* -s: silent mode (ignore errors) */
81 int vflag
; /* -v: only show non-matching lines */
82 int wflag
; /* -w: pattern must start and end on word boundaries */
83 int xflag
; /* -x: pattern must match entire line */
84 int lbflag
; /* --line-buffered */
86 int binbehave
= BIN_FILE_BIN
;
89 BIN_OPT
= CHAR_MAX
+ 1,
96 int first
; /* flag whether or not this is our first match */
97 int tail
; /* lines left to print */
101 SLIST_ENTRY(patfile
) pf_next
;
103 SLIST_HEAD(, patfile
) patfilelh
;
110 "usage: %s [-abcEFGHhIiLlnoPqRSsUVvwx] [-A num] [-B num] [-C[num]]\n"
112 "usage: %s [-abcEFGHhIiLlnoPqRSsUVvwxZ] [-A num] [-B num] [-C[num]]\n"
114 "\t[-e pattern] [-f file] [--binary-files=value] [--context[=num]]\n"
115 "\t[--line-buffered] [pattern] [file ...]\n", getprogname());
120 static char *optstr
= "0123456789A:B:CEFGHILPSRUVabce:f:hilnoqrsuvwxy";
122 static char *optstr
= "0123456789A:B:CEFGHILPSRUVZabce:f:hilnoqrsuvwxy";
125 struct option long_options
[] =
127 {"binary-files", required_argument
, NULL
, BIN_OPT
},
128 {"help", no_argument
, NULL
, HELP_OPT
},
129 {"mmap", no_argument
, NULL
, MMAP_OPT
},
130 {"line-buffered", no_argument
, NULL
, LINEBUF_OPT
},
131 {"after-context", required_argument
, NULL
, 'A'},
132 {"before-context", required_argument
, NULL
, 'B'},
133 {"context", optional_argument
, NULL
, 'C'},
134 {"devices", required_argument
, NULL
, 'D'},
135 {"extended-regexp", no_argument
, NULL
, 'E'},
136 {"fixed-strings", no_argument
, NULL
, 'F'},
137 {"basic-regexp", no_argument
, NULL
, 'G'},
138 {"binary", no_argument
, NULL
, 'U'},
139 {"version", no_argument
, NULL
, 'V'},
140 {"text", no_argument
, NULL
, 'a'},
141 {"byte-offset", no_argument
, NULL
, 'b'},
142 {"count", no_argument
, NULL
, 'c'},
143 {"regexp", required_argument
, NULL
, 'e'},
144 {"file", required_argument
, NULL
, 'f'},
145 {"no-filename", no_argument
, NULL
, 'h'},
146 {"ignore-case", no_argument
, NULL
, 'i'},
147 {"files-without-match", no_argument
, NULL
, 'L'},
148 {"files-with-matches", no_argument
, NULL
, 'l'},
149 {"line-number", no_argument
, NULL
, 'n'},
150 {"quiet", no_argument
, NULL
, 'q'},
151 {"silent", no_argument
, NULL
, 'q'},
152 {"recursive", no_argument
, NULL
, 'r'},
153 {"no-messages", no_argument
, NULL
, 's'},
154 {"revert-match", no_argument
, NULL
, 'v'},
155 {"word-regexp", no_argument
, NULL
, 'w'},
156 {"line-regexp", no_argument
, NULL
, 'x'},
157 {"unix-byte-offsets", no_argument
, NULL
, 'u'},
159 {"decompress", no_argument
, NULL
, 'Z'},
161 {NULL
, no_argument
, NULL
, 0}
166 add_pattern(char *pat
, size_t len
)
168 if (!xflag
&& (len
== 0 || matchall
)) {
172 if (patterns
== pattern_sz
) {
174 pattern
= grep_realloc(pattern
, ++pattern_sz
* sizeof(*pattern
));
176 if (len
> 0 && pat
[len
- 1] == '\n')
178 /* pat may not be NUL-terminated */
179 if (wflag
&& !Fflag
) {
180 int bol
= 0, eol
= 0, extra
;
183 if (len
> 0 && pat
[len
- 1] == '$')
185 extra
= Eflag
? 2 : 4;
186 pattern
[patterns
] = grep_malloc(len
+ 15 + extra
);
187 snprintf(pattern
[patterns
], len
+ 15 + extra
,
188 "%s[[:<:]]%s%.*s%s[[:>:]]%s",
191 (int)len
- bol
- eol
, pat
+ bol
,
196 pattern
[patterns
] = grep_malloc(len
+ 1);
197 memcpy(pattern
[patterns
], pat
, len
);
198 pattern
[patterns
][len
] = '\0';
204 add_patterns(char *pats
)
208 while ((nl
= strchr(pats
, '\n')) != NULL
) {
209 add_pattern(pats
, nl
- pats
);
212 add_pattern(pats
, strlen(pats
));
216 read_patterns(const char *fn
)
222 if ((f
= fopen(fn
, "r")) == NULL
)
224 while ((line
= fgetln(f
, &len
)) != NULL
)
225 add_pattern(line
, *line
== '\n' ? 0 : len
);
232 main(int argc
, char *argv
[])
234 int c
, lastc
, prevoptind
, newarg
, i
, needpattern
;
235 struct patfile
*patfile
, *pf_next
;
239 SLIST_INIT(&patfilelh
);
241 switch (getprogname()[0]) {
254 switch(getprogname()[1]) {
273 while ((c
= getopt_long(argc
, argv
, optstr
,
274 long_options
, NULL
)) != -1) {
276 case '0': case '1': case '2': case '3': case '4':
277 case '5': case '6': case '7': case '8': case '9':
278 if (newarg
|| !isdigit(lastc
))
280 else if (Aflag
> INT_MAX
/ 10)
281 errx(2, "context out of range");
282 Aflag
= Bflag
= (Aflag
* 10) + (c
- '0');
286 l
= strtol(optarg
, &ep
, 10);
287 if (ep
== optarg
|| *ep
!= '\0' ||
288 l
<= 0 || l
>= INT_MAX
)
289 errx(2, "context out of range");
299 l
= strtol(optarg
, &ep
, 10);
300 if (ep
== optarg
|| *ep
!= '\0' ||
301 l
<= 0 || l
>= INT_MAX
)
302 errx(2, "context out of range");
303 Aflag
= Bflag
= (int)l
;
322 binbehave
= BIN_FILE_SKIP
;
340 binbehave
= BIN_FILE_BIN
;
343 fprintf(stderr
, "grep version %u.%u\n", VER_MAJ
, VER_MIN
);
352 binbehave
= BIN_FILE_TEXT
;
361 add_patterns(optarg
);
365 patfile
= grep_malloc(sizeof(*patfile
));
366 patfile
->pf_file
= optarg
;
367 SLIST_INSERT_HEAD(&patfilelh
, patfile
, pf_next
);
406 if (strcmp("binary", optarg
) == 0)
407 binbehave
= BIN_FILE_BIN
;
408 else if (strcmp("without-match", optarg
) == 0)
409 binbehave
= BIN_FILE_SKIP
;
410 else if (strcmp("text", optarg
) == 0)
411 binbehave
= BIN_FILE_TEXT
;
413 errx(2, "Unknown binary-files option");
417 /* default, compatibility */
427 newarg
= optind
!= prevoptind
;
433 for (patfile
= SLIST_FIRST(&patfilelh
); patfile
!= NULL
;
435 pf_next
= SLIST_NEXT(patfile
, pf_next
);
436 read_patterns(patfile
->pf_file
);
440 if (argc
== 0 && needpattern
)
443 if (argc
!= 0 && needpattern
) {
450 cflags
|= REG_EXTENDED
;
451 fg_pattern
= grep_calloc(patterns
, sizeof(*fg_pattern
));
452 r_pattern
= grep_calloc(patterns
, sizeof(*r_pattern
));
453 for (i
= 0; i
< patterns
; ++i
) {
454 /* Check if cheating is allowed (always is for fgrep). */
456 fgrepcomp(&fg_pattern
[i
], pattern
[i
]);
458 if (fastcomp(&fg_pattern
[i
], pattern
[i
])) {
459 /* Fall back to full regex library */
460 c
= regcomp(&r_pattern
[i
], pattern
[i
], cflags
);
462 regerror(c
, &r_pattern
[i
], re_error
,
464 errx(2, "%s", re_error
);
475 if ((argc
== 0 || argc
== 1) && !oflag
)
479 exit(!procfile(NULL
));
484 for (c
= 0; argc
--; ++argv
)
485 c
+= procfile(*argv
);