blob: 3bfb8ea546df0b1ca9d0aac71658a751ade1928e [file] [log] [blame]
Jakub Koturc72d7202020-12-21 17:28:15 +01001use std::env;
2use std::error::Error;
3use std::io;
4use std::process;
5
6fn run() -> Result<(), Box<dyn Error>> {
7 // Get the query from the positional arguments.
8 // If one doesn't exist, return an error.
9 let query = match env::args().nth(1) {
10 None => return Err(From::from("expected 1 argument, but got none")),
11 Some(query) => query,
12 };
13
14 // Build CSV readers and writers to stdin and stdout, respectively.
15 let mut rdr = csv::Reader::from_reader(io::stdin());
16 let mut wtr = csv::Writer::from_writer(io::stdout());
17
18 // Before reading our data records, we should write the header record.
19 wtr.write_record(rdr.headers()?)?;
20
21 // Iterate over all the records in `rdr`, and write only records containing
22 // `query` to `wtr`.
23 for result in rdr.records() {
24 let record = result?;
25 if record.iter().any(|field| field == &query) {
26 wtr.write_record(&record)?;
27 }
28 }
29
30 // CSV writers use an internal buffer, so we should always flush when done.
31 wtr.flush()?;
32 Ok(())
33}
34
35fn main() {
36 if let Err(err) = run() {
37 println!("{}", err);
38 process::exit(1);
39 }
40}