Search a file for lines matching a regular expression pattern. Return the line number and contents of each matching line.
The Unix grep
command can be used to search for lines in one or more files
that match a user-provided search query (known as the pattern).
The grep
command takes three arguments:
- The pattern used to match lines in a file.
- Zero or more flags to customize the matching behavior.
- One or more files in which to search for matching lines.
Your task is to implement the grep
function, which should read the contents
of the specified files, find the lines that match the specified pattern
and then output those lines as a single string. Note that the lines should
be output in the order in which they were found, with the first matching line
in the first file being output first.
As an example, suppose there is a file named "input.txt" with the following contents:
hello
world
hello again
If we were to call grep "hello" input.txt
, the returned string should be:
hello
hello again
As said earlier, the grep
command should also support the following flags:
-n
Print the line numbers of each matching line.-l
Print only the names of files that contain at least one matching line.-i
Match line using a case-insensitive comparison.-v
Invert the program -- collect all lines that fail to match the pattern.-x
Only match entire lines, instead of lines that contain a match.
If we run grep -n "hello" input.txt
, the -n
flag will require the matching
lines to be prefixed with its line number:
1:hello
3:hello again
And if we run grep -i "HELLO" input.txt
, we'll do a case-insensitive match,
and the output will be:
hello
hello again
The grep
command should support multiple flags at once.
For example, running grep -l -v "hello" file1.txt file2.txt
should
print the names of files that do not contain the string "hello".
For installation and learning resources, refer to the Ruby resources page.
For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:
gem install minitest
If you would like color output, you can require 'minitest/pride'
in
the test file, or note the alternative instruction, below, for running
the test file.
Run the tests from the exercise directory using the following command:
ruby grep_test.rb
To include color from the command line:
ruby -r minitest/pride grep_test.rb
Conversation with Nate Foster. http://www.cs.cornell.edu/Courses/cs3110/2014sp/hw/0/ps0.pdf
It's possible to submit an incomplete solution so you can see how others have completed the exercise.