Skip to content

Instantly share code, notes, and snippets.

Created December 28, 2016 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/bfa42d4f86e03695f3c880aaceca2088 to your computer and use it in GitHub Desktop.
Save anonymous/bfa42d4f86e03695f3c880aaceca2088 to your computer and use it in GitHub Desktop.
extern crate regex;
use std::env;
use std::error;
use std::fs::File;
use std::io::{self, BufRead, Write};
use std::process;
use regex::bytes::Regex;
type Error = Box<error::Error + Send + Sync>;
fn main() {
match run() {
Ok(count) => println!("{}", count),
Err(err) => {
let _ = writeln!(&mut io::stderr(), "{}", err);
process::exit(1);
}
}
}
fn run() -> Result<u64, Error> {
let (fpath, query) = match (env::args_os().nth(1), env::args().nth(2)) {
(None, _) => return Err(Error::from("missing file to search")),
(_, None) => return Err(Error::from("missing search query")),
(Some(fpath), Some(query)) => (fpath, query),
};
let query_re = Regex::new(&regex::quote(&query))?;
let mut count = 0;
let mut rdr = io::BufReader::new(File::open(fpath)?);
let mut line = vec![];
while rdr.read_until(b'\n', &mut line)? > 0 {
if query_re.is_match(&line) {
count += 1;
}
line.clear();
}
Ok(count)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment