DEV Community


Minigrep : grep using Rust

niran_jana profile image Niranjana ・2 min read

grep (Global Regular Expression Print)is a command-line utility for searching plain-text data sets for lines that match a regular expression.
Minigrep is a simple rust program that recreates the basic functions of grep alongside providing few more addition features:
1.Case-insensitive search can be done by passing an option.
2.Ability to do exact-match search.
3.The query is highlighted in the output.

The aim of the program is to be able to search for word in a given a text file. It goes by the following format:

CASE_INSENSITIVE=1 cargo run “word to be searched” “filename” > “output file”

Miniproject follows Test-driven development (TDD) process. This is a software development technique that uses the method of writing a test that fails for a reason expected and later modifying the code to make new test pass. This is followed by refactoring the code and continuing to ensure that the tests pass. Writing the test before you write the code that makes the test pass helps to maintain high test coverage throughout the process.
The logic behind Minigrep can be explained with its main struct and run function.

pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
//run function
pub fn run(config: Config) -> Result> {
let contents = fs::read_to_string(config.filename)?;
let results = if config.case_sensitive {
search(&config.query, &contents)
} else {
search_case_insensitive(&config.query, &contents)
for line in results {
println!(“{}”, line);

The program can be broken down into 5 parts:
1.Accepting command line arguments
2.Reading a file
3.Writing tests an developing library
4.Setting up environment variable
5.Writing error messages to standard error
6.Throughout these steps, we use refactoring to make the
program more efficient.
For instance, the program began with the basic lines of code

use std::env;
fn main() {
 let args: Vec = env::args().collect();
let query = &args[1];
let filename = &args[2];
println!(“Searching for {}”, query);
 println!(“In file {}”, filename);

This was further developed into a struct seeing repetitions. The query and filename along with case sensitive boolean were added to the structure Config.
To see more of how the logic panned into run() function, the tests and library along with directions of use, please find the source code on GitHub.

Discussion (0)

Editor guide