Search file, display pattern matches, return true when pattern matched anywhere
| 543 | |
| 544 | // Search file, display pattern matches, return true when pattern matched anywhere |
| 545 | bool ugrep(reflex::Pattern& pattern, FILE *file, reflex::Input::file_encoding_type encoding, const char *infile) |
| 546 | { |
| 547 | bool found = false; |
| 548 | |
| 549 | std::string label, mark, unmark; |
| 550 | |
| 551 | if (flag_filename && infile) |
| 552 | label.assign(infile).append(":"); |
| 553 | |
| 554 | if (grep_color) |
| 555 | { |
| 556 | mark.assign("\033[").append(grep_color).append("m"); |
| 557 | unmark.assign("\033[0m"); |
| 558 | } |
| 559 | |
| 560 | // create an input object to read the file (or stdin) using the given file format encoding |
| 561 | reflex::Input input(file, encoding); |
| 562 | |
| 563 | if (flag_quiet) |
| 564 | { |
| 565 | // -q quiet mode: report if a single pattern match was found in the input |
| 566 | |
| 567 | found = reflex::Matcher(pattern, input).find(); |
| 568 | |
| 569 | if (flag_invert_match) |
| 570 | found = !found; |
| 571 | } |
| 572 | else if (flag_count) |
| 573 | { |
| 574 | // -c count mode: count the number of lines/patterns matched |
| 575 | |
| 576 | if (flag_invert_match) |
| 577 | { |
| 578 | size_t lines = 0; |
| 579 | std::string line; |
| 580 | |
| 581 | // -c count mode w/ -v: count the number of non-matching lines |
| 582 | while (input) |
| 583 | { |
| 584 | int ch; |
| 585 | |
| 586 | // read the next line |
| 587 | line.clear(); |
| 588 | while ((ch = input.get()) != EOF && ch != '\n') |
| 589 | line.push_back(ch); |
| 590 | if (ch == EOF && line.empty()) |
| 591 | break; |
| 592 | |
| 593 | // count this line if not matched |
| 594 | if (!reflex::Matcher(pattern, line).find()) |
| 595 | { |
| 596 | found = true; |
| 597 | ++lines; |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | std::cout << label << lines << std::endl; |
| 602 | } |