First implementation of grrs

After the last chapter on command line arguments, we have our input data, and we can start to write our actual tool. Our main function only contains this line right now:

    let args = Cli::parse();

(We drop the println statement that we merely put there temporarily to demonstrate that our program works as expected.)

Let’s start by opening the file we got.

    let content = std::fs::read_to_string(&args.path).expect("could not read file");

Now, let’s iterate over the lines and print each one that contains our pattern:

    for line in content.lines() {
        if line.contains(&args.pattern) {
            println!("{}", line);
        }
    }

Wrapping up

Your code should now look like:

use clap::Parser;

/// Search for a pattern in a file and display the lines that contain it.
#[derive(Parser)]
struct Cli {
    /// The pattern to look for
    pattern: String,
    /// The path to the file to read
    path: std::path::PathBuf,
}

fn main() {
    let args = Cli::parse();
    let content = std::fs::read_to_string(&args.path).expect("could not read file");

    for line in content.lines() {
        if line.contains(&args.pattern) {
            println!("{}", line);
        }
    }
}

Give it a try: cargo run -- main src/main.rs should work now!