Instantly share code, notes, and snippets.

Embed
What would you like to do?
[package]
name = "steves-csv-thingy"
version = "0.1.0"
authors = ["Pascal Hertleif <killercup@gmail.com>"]
[[bin]]
name = "quicsv"
path = "main.rs"
[dependencies]
quicli = "0.2.0"
csv = "1.0.0-beta.5"
serde = "1.0.27"
#[macro_use] extern crate quicli;
extern crate csv;
use quicli::prelude::*;
#[derive(Debug, Serialize, Deserialize)]
struct Record<'a> {
name: &'a str,
surname: &'a str,
city: &'a str,
country: &'a str,
}
#[derive(StructOpt, Debug)]
struct Opt {
filename: String,
column_name: String,
replacement: String,
output_filename: String,
}
main!(|args: Opt| {
use std::fs::File;
let input = File::open(&args.filename)?;
let output = File::create(&args.output_filename)?;
let mut rdr = csv::Reader::from_reader(input);
let mut wtr = csv::Writer::from_writer(output);
let mut raw_record = csv::StringRecord::new();
let headers = rdr.headers()?.clone();
while rdr.read_record(&mut raw_record)? {
let mut record: Record = raw_record.deserialize(Some(&headers))?;
match &*args.column_name {
"name" => record.name = &args.replacement,
"surname" => record.surname = &args.replacement,
"city" => record.city = &args.replacement,
"country" => record.country = &args.replacement,
_ => panic!("incorrect column name"),
}
wtr.serialize(record)?;
}
wtr.flush()?;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment