From 96922e7d1fa6a02a4d8373828345d00326d2b799 Mon Sep 17 00:00:00 2001 From: Joursoir Date: Tue, 7 Mar 2023 19:04:00 +0400 Subject: add option to count of the number of lines that match a pattern --- src/main.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main.rs b/src/main.rs index b566f68..2d1de95 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,6 +28,10 @@ struct Config { #[arg(short = 'v', long)] invert_match: bool, + /// Displays only a count of the number of lines that match the search string + #[arg(short, long)] + count: bool, + /// Prefixes each matching line with the line number #[arg(short = 'n', long)] line_number: bool, @@ -65,6 +69,7 @@ fn main() { fn run(config: Config) -> Result<(), Box> { 'outer: for file in config.files { + let mut count: usize = 0; // On-Stack Dynamic Dispatch let (mut stdin_read, mut file_read); @@ -87,6 +92,9 @@ fn run(config: Config) -> Result<(), Box> { if config.files_with_matches { println!("{file}"); continue 'outer; + } else if config.count { + count += 1; + continue; } let formatted_output = if !config.no_filename && config.line_number { @@ -101,6 +109,10 @@ fn run(config: Config) -> Result<(), Box> { println!("{}", formatted_output); } + + if config.count { + println!("{}:{}", file, count); + } } Ok(()) -- cgit v1.2.3-18-g5258