Chapter 9. Jack the Grepper
Please explain the expression on your face
They Might Be Giants, “Unrelated Thing” (1994)
In this chapter, you will write a Rust version of grep, which will find lines of input that match a given regular expression.1
By default the input comes from STDIN, but you can provide the names of one or more files or directories if you use a recursive option to find all the files in those directories.
The normal output will be the lines that match the given pattern, but you can invert the match to find the lines that don’t match.
You can also instruct grep to print the number of matching lines instead of the lines of text.
Pattern matching is normally case-sensitive, but you can use an option to perform case-insensitive matching.
While the original program can do more, the challenge program will go only this far.
In writing this program, you’ll learn about:
-
Using a case-sensitive regular expression
-
Variations of regular expression syntax
-
Another syntax to indicate a trait bound
-
Using Rust’s bitwise exclusive-OR operator
How grep Works
I’ll start by showing the manual page for the BSD grep to give you a sense of the many options the command will accept:
GREP(1) BSD General Commands Manual GREP(1) NAME grep, egrep, fgrep, zgrep, zegrep, zfgrep -- file pattern searcher SYNOPSIS grep [-abcdDEFGHhIiJLlmnOopqRSsUVvwxZ] [-A num] [-B num] [-C[num]] [-e pattern] [-f file] [--binary-files=value] [--color[=when]] [--colour[=when]] [--context[=num]] [--label] ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access