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