grep.c (12893B)
1 2 #include "config.h" 3 #include "queue.h" 4 #include "util.h" 5 6 #include <regex.h> 7 #include <stdio.h> 8 #include <stdlib.h> 9 #include <string.h> 10 #include <strings.h> 11 12 enum { Match = 0, NoMatch = 1, Error = 2 }; 13 14 static void addpattern(const char *); 15 static void addpatternfile(FILE *); 16 static int grep(FILE *, const char *); 17 18 // true if argv0's own basename is exactly name, ignoring any path prefix 19 static int 20 invoked_as(const char *name) 21 { 22 const char *base = strrchr(argv0, '/'); 23 base = base ? base + 1 : argv0; 24 return strcmp(base, name) == 0; 25 } 26 27 static int Eflag; 28 static int Fflag; 29 static int Hflag; 30 static int eflag; 31 static int fflag; 32 static int hflag; 33 static int iflag; 34 static int oflag; 35 static int sflag; 36 static int vflag; 37 static int wflag; 38 static int xflag; 39 static int many; 40 static int mode; 41 #if FEATURE_GREP_CONTEXT 42 static long Aflag = 0; 43 static long Bflag = 0; 44 #endif 45 #if FEATURE_GREP_MAX_COUNT 46 static long mval = -1; 47 #endif 48 49 struct pattern { 50 regex_t preg; 51 SLIST_ENTRY(pattern) entry; 52 char pattern[]; 53 }; 54 55 static SLIST_HEAD(phead, pattern) phead; 56 57 static void 58 addpattern(const char *pattern) 59 { 60 struct pattern *pnode; 61 size_t patlen; 62 63 patlen = strlen(pattern); 64 65 pnode = enmalloc(Error, sizeof(*pnode) + patlen + 9); 66 SLIST_INSERT_HEAD(&phead, pnode, entry); 67 68 if (Fflag || (!xflag && !wflag)) { 69 memcpy(pnode->pattern, pattern, patlen + 1); 70 } else { 71 sprintf( 72 pnode->pattern, 73 "%s%s%s%s%s", 74 xflag ? "^" : "\\<", 75 Eflag ? "(" : "\\(", 76 pattern, 77 Eflag ? ")" : "\\)", 78 xflag ? "$" : "\\>" 79 ); 80 } 81 } 82 83 static void 84 addpatternfile(FILE *fp) 85 { 86 static char *buf = NULL; 87 static size_t size = 0; 88 ssize_t len = 0; 89 90 while ((len = getline(&buf, &size, fp)) > 0) { 91 if (buf[len - 1] == '\n') 92 buf[len - 1] = '\0'; 93 addpattern(buf); 94 } 95 if (ferror(fp)) 96 enprintf(Error, "read error:"); 97 } 98 99 #if FEATURE_GREP_CONTEXT 100 static void 101 print_line(const char *str, const char *line, long line_no, char sep) 102 { 103 if (!hflag && (many || Hflag)) 104 printf("%s%c", str, sep); 105 if (mode == 'n') 106 printf("%ld%c", line_no, sep); 107 puts(line); 108 } 109 #endif 110 111 // the leftmost longest match of any pattern in text, its offset and length. 112 // notbol is set once part of the line is behind us, so ^ matches nothing 113 // in the middle of it 114 static int 115 firstmatch(const char *text, int notbol, size_t *at, size_t *len) 116 { 117 struct pattern *pnode; 118 regmatch_t pm; 119 const char *hit; 120 size_t o, l; 121 int found = 0; 122 123 SLIST_FOREACH(pnode, &phead, entry) 124 { 125 if (Fflag) { 126 if (!(hit = (iflag ? strcasestr : strstr)(text, pnode->pattern))) 127 continue; 128 o = hit - text; 129 l = strlen(pnode->pattern); 130 } else { 131 if (regexec(&pnode->preg, text, 1, &pm, notbol ? REG_NOTBOL : 0)) 132 continue; 133 o = pm.rm_so; 134 l = pm.rm_eo - pm.rm_so; 135 } 136 if (!found || o < *at || (o == *at && l > *len)) { 137 *at = o; 138 *len = l; 139 found = 1; 140 } 141 } 142 return found; 143 } 144 145 // -o: each match on a line of its own, with the prefix a whole line has 146 static void 147 print_matches(const char *str, const char *line, long line_no) 148 { 149 size_t at, len; 150 int notbol = 0; 151 152 while (*line && firstmatch(line, notbol, &at, &len)) { 153 if (!len) { 154 // an empty match says nothing, step over a character 155 line++; 156 notbol = 1; 157 continue; 158 } 159 if (!hflag && (many || Hflag)) 160 printf("%s:", str); 161 if (mode == 'n') 162 printf("%ld:", line_no); 163 printf("%.*s\n", (int)len, line + at); 164 line += at + len; 165 notbol = 1; 166 } 167 } 168 169 static int 170 grep(FILE *fp, const char *str) 171 { 172 static char *buf = NULL; 173 static size_t size = 0; 174 ssize_t len = 0; 175 long c = 0, n; 176 struct pattern *pnode; 177 int match, result = NoMatch; 178 #if FEATURE_GREP_MAX_COUNT 179 long matches = 0; 180 #endif 181 #if FEATURE_GREP_CONTEXT 182 struct context_line { 183 char *str; 184 long line_no; 185 } *before_buf = NULL; 186 size_t before_head = 0, before_count = 0, i = 0, idx = 0; 187 long after_left = 0; 188 long last_printed_line = 0; 189 190 if (Bflag > 0 && !(mode == 'c' || mode == 'l' || mode == 'q')) 191 before_buf = ecalloc(Bflag, sizeof(*before_buf)); 192 #endif 193 194 for (n = 1; (len = getline(&buf, &size, fp)) > 0; n++) { 195 /* remove the trailing newline if one is present */ 196 if (buf[len - 1] == '\n') 197 buf[len - 1] = '\0'; 198 match = 0; 199 SLIST_FOREACH(pnode, &phead, entry) 200 { 201 if (Fflag) { 202 if (xflag) { 203 if (!(iflag ? strcasecmp : strcmp)(buf, pnode->pattern)) { 204 match = 1; 205 break; 206 } 207 } else { 208 if ((iflag ? strcasestr : strstr)(buf, pnode->pattern)) { 209 match = 1; 210 break; 211 } 212 } 213 } else { 214 if (regexec(&pnode->preg, buf, 0, NULL, 0) == 0) { 215 match = 1; 216 break; 217 } 218 } 219 } 220 if (match != vflag) { 221 result = Match; 222 #if FEATURE_GREP_MAX_COUNT 223 matches++; 224 #endif 225 switch (mode) { 226 case 'c': 227 c++; 228 break; 229 case 'l': 230 puts(str); 231 goto end; 232 case 'q': 233 exit(Match); 234 default: 235 #if FEATURE_GREP_CONTEXT 236 if (Aflag > 0 || Bflag > 0) { 237 if (last_printed_line > 0 && n > last_printed_line + 1) 238 puts("--"); 239 for (i = 0; i < before_count; i++) { 240 idx = (before_head - before_count + i + Bflag) % Bflag; 241 print_line(str, before_buf[idx].str, before_buf[idx].line_no, '-'); 242 free(before_buf[idx].str); 243 before_buf[idx].str = NULL; 244 } 245 before_count = 0; 246 before_head = 0; 247 print_line(str, buf, n, ':'); 248 after_left = Aflag; 249 last_printed_line = n; 250 } else { 251 #endif 252 if (oflag && !vflag) { 253 print_matches(str, buf, n); 254 break; 255 } 256 if (!hflag && (many || Hflag)) 257 printf("%s:", str); 258 if (mode == 'n') 259 printf("%ld:", n); 260 puts(buf); 261 #if FEATURE_GREP_CONTEXT 262 } 263 #endif 264 break; 265 } 266 #if FEATURE_GREP_MAX_COUNT 267 if (mval >= 0 && matches >= mval) 268 goto end; 269 #endif 270 } 271 #if FEATURE_GREP_CONTEXT 272 else if (Aflag > 0 || Bflag > 0) { 273 if (mode != 'c' && mode != 'l' && mode != 'q') { 274 if (after_left > 0) { 275 print_line(str, buf, n, '-'); 276 after_left--; 277 last_printed_line = n; 278 } 279 if (Bflag > 0) { 280 if (before_count == (size_t)Bflag) 281 free(before_buf[before_head].str); 282 before_buf[before_head].str = estrdup(buf); 283 before_buf[before_head].line_no = n; 284 before_head = (before_head + 1) % Bflag; 285 if (before_count < (size_t)Bflag) 286 before_count++; 287 } 288 } 289 } 290 #endif 291 } 292 if (mode == 'c') 293 printf("%ld\n", c); 294 end: 295 #if FEATURE_GREP_CONTEXT 296 if (before_buf) { 297 for (i = 0; i < (size_t)Bflag; i++) 298 free(before_buf[i].str); 299 free(before_buf); 300 } 301 #endif 302 if (ferror(fp)) { 303 weprintf("%s: read error:", str); 304 result = Error; 305 } 306 return result; 307 } 308 309 static void 310 usage(void) 311 { 312 enprintf( 313 Error, 314 "usage: %s [-EFHchilnoqsvwx]" 315 #if FEATURE_GREP_CONTEXT 316 " [-A num] [-B num] [-C num]" 317 #endif 318 #if FEATURE_GREP_MAX_COUNT 319 " [-m num]" 320 #endif 321 " [-e pattern] [-f file] [pattern] [file ...]\n", 322 argv0 323 ); 324 } 325 326 // ?man grep: search files for a pattern 327 // ?man arguments: pattern [file ...] 328 // ?man grep searches the named input files for lines matching the given pattern 329 // ?man if no files are named, or a file is -, standard input is searched 330 // ?man by default, matching lines are written to standard output 331 int 332 main(int argc, char *argv[]) 333 { 334 struct pattern *pnode; 335 int m, flags = REG_NOSUB, match = NoMatch; 336 FILE *fp; 337 char *arg; 338 339 SLIST_INIT(&phead); 340 argv0 = argv[0]; 341 342 // egrep/fgrep: legacy invocation names many upstream scripts still 343 // assume exist as their own commands rather than as grep -E/-F 344 if (invoked_as("egrep")) { 345 Eflag = 1; 346 flags |= REG_EXTENDED; 347 } else if (invoked_as("fgrep")) { 348 Fflag = 1; 349 } 350 351 ARGBEGIN 352 { 353 #if FEATURE_GREP_CONTEXT 354 // ?man -A:num: print num lines of trailing context after each match 355 case 'A': 356 Aflag = estrtonum(EARGF(usage()), 0, LONG_MAX); 357 break; 358 // ?man -B:num: print num lines of leading context before each match 359 case 'B': 360 Bflag = estrtonum(EARGF(usage()), 0, LONG_MAX); 361 break; 362 // ?man -C:num: print num lines of context before and after each match 363 case 'C': 364 Aflag = Bflag = estrtonum(EARGF(usage()), 0, LONG_MAX); 365 break; 366 // ?man ARGNUM: specify RGNUM option 367 ARGNUM: 368 Aflag = Bflag = ARGNUMF(); 369 break; 370 #endif 371 #if FEATURE_GREP_MAX_COUNT 372 // ?man -m:num: stop reading a file after num matching lines 373 case 'm': 374 mval = estrtonum(EARGF(usage()), 0, LONG_MAX); 375 break; 376 #endif 377 case 'E': 378 // ?man -E: interpret pattern as an extended regular expression 379 Eflag = 1; 380 Fflag = 0; 381 flags |= REG_EXTENDED; 382 break; 383 case 'F': 384 // ?man -F: interpret pattern as a list of fixed strings separated by newlines 385 Fflag = 1; 386 Eflag = 0; 387 flags &= ~REG_EXTENDED; 388 break; 389 case 'H': 390 // ?man -H: always print the file name with matching lines 391 Hflag = 1; 392 hflag = 0; 393 break; 394 // ?man -e:file: specify a pattern to match; may be given multiple times 395 case 'e': 396 arg = EARGF(usage()); 397 if (!(fp = fmemopen(arg, strlen(arg) + 1, "r"))) 398 eprintf("fmemopen:"); 399 addpatternfile(fp); 400 efshut(fp, arg); 401 eflag = 1; 402 break; 403 // ?man -f:file: read patterns from file, one per line 404 case 'f': 405 arg = EARGF(usage()); 406 fp = fopen(arg, "r"); 407 if (!fp) 408 enprintf(Error, "fopen %s:", arg); 409 addpatternfile(fp); 410 efshut(fp, arg); 411 fflag = 1; 412 break; 413 case 'h': 414 // ?man -h: never print file names with matching lines 415 hflag = 1; 416 Hflag = 0; 417 break; 418 case 'c': 419 // ?man -c: print only a count of matching lines per file 420 /* FALLTHROUGH */ 421 case 'l': 422 // ?man -l: print only the names of files with at least one matching line 423 /* FALLTHROUGH */ 424 case 'n': 425 // ?man -n: prefix each matching line with its line number within its file 426 /* FALLTHROUGH */ 427 case 'q': 428 // ?man -q: quiet mode; exit immediately with status 0 on first match and write nothing 429 mode = ARGC(); 430 break; 431 case 'i': 432 // ?man -i: perform case-insensitive matching 433 flags |= REG_ICASE; 434 iflag = 1; 435 break; 436 case 'o': 437 // ?man -o: print only the matching parts of a line, each on a line of its own 438 oflag = 1; 439 flags &= ~REG_NOSUB; 440 break; 441 case 's': 442 // ?man -s: suppress error messages about nonexistent or unreadable files 443 sflag = 1; 444 break; 445 case 'v': 446 // ?man -v: invert the sense of matching to select non-matching lines 447 vflag = 1; 448 break; 449 case 'w': 450 // ?man -w: match only whole words 451 wflag = 1; 452 break; 453 case 'x': 454 // ?man -x: match only whole lines 455 xflag = 1; 456 break; 457 default: 458 usage(); 459 } 460 ARGEND 461 462 if (argc == 0 && !eflag && !fflag) 463 usage(); /* no pattern */ 464 465 /* just add literal pattern to list */ 466 if (!eflag && !fflag) { 467 if (!(fp = fmemopen(argv[0], strlen(argv[0]) + 1, "r"))) 468 eprintf("fmemopen:"); 469 addpatternfile(fp); 470 efshut(fp, argv[0]); 471 argc--; 472 argv++; 473 } 474 475 if (!Fflag) 476 /* compile regex for all search patterns */ 477 SLIST_FOREACH(pnode, &phead, entry) 478 enregcomp(Error, &pnode->preg, pnode->pattern, flags); 479 many = (argc > 1); 480 if (argc == 0) { 481 match = grep(stdin, "<stdin>"); 482 } else { 483 for (; *argv; argc--, argv++) { 484 if (!strcmp(*argv, "-")) { 485 *argv = "<stdin>"; 486 fp = stdin; 487 } else if (!(fp = fopen(*argv, "r"))) { 488 if (!sflag) 489 weprintf("fopen %s:", *argv); 490 match = Error; 491 continue; 492 } 493 m = grep(fp, *argv); 494 if (m == Error || (match != Error && m == Match)) 495 match = m; 496 if (fp != stdin && fshut(fp, *argv)) 497 match = Error; 498 } 499 } 500 501 if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>")) 502 match = Error; 503 504 // ?man 505 // ?man ## Exit status 506 // ?man 507 // ?man 0 508 // ?man : one or more lines matched in at least one file 509 // ?man 510 // ?man 1 511 // ?man : no lines matched in any file 512 // ?man 513 // ?man 2 514 // ?man : an error occurred 515 // ?man 516 // ?man ## See also 517 // ?man 518 // ?man sed(1), awk(1) 519 // ?man 520 521 return match; 522 }