Skip to content

Instantly share code, notes, and snippets.

@yujp
Last active February 11, 2020 07:59
Show Gist options
  • Select an option

  • Save yujp/3e40a505f2db1b6ba509a2a4ac3a133e to your computer and use it in GitHub Desktop.

Select an option

Save yujp/3e40a505f2db1b6ba509a2a4ac3a133e to your computer and use it in GitHub Desktop.
use std::env;
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, Write, BufWriter};
use std::collections::HashMap;
use chrono::{DateTime, Local};
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("file name must be specified.");
return;
}
let filename = &args[1];
let file = File::open(filename).unwrap_or_else(|e| {
panic!("failed to open file: {}", e);
});
let reader = BufReader::new(file);
let mut date_map: HashMap<String, u64> = HashMap::new();
for (_index, line) in reader.lines().enumerate() {
let line = line.unwrap();
let date = get_date(&line);
let dt = DateTime::parse_from_str(date, "%d/%b/%Y:%H:%M:%S %z").unwrap();
let date = dt.with_timezone(&Local).format("%Y%m%d").to_string();
let count = date_map.entry(String::from(date)).or_insert(0);
*count += 1;
}
let mut writers: HashMap<String, _> = HashMap::new();
for (date, _count) in date_map {
let ds = String::from(&date);
let fname = format!("{}.log", &date);
let fo = OpenOptions::new()
.write(true)
.truncate(false)
.append(true)
.create(true)
.open(fname)
.unwrap();
let fw = BufWriter::new(fo);
writers.insert(ds, fw);
}
let file = File::open(filename).unwrap_or_else(|e| {
panic!("failed to open file: {}", e);
});
let reader = BufReader::new(file);
for (_index, line) in reader.lines().enumerate() {
let line = line.unwrap();
let date = get_date(&line);
let dt = DateTime::parse_from_str(date, "%d/%b/%Y:%H:%M:%S %z").unwrap();
let ds = dt.with_timezone(&Local).format("%Y%m%d").to_string();
let w = writers.get_mut(&ds).unwrap();
writeln!(w, "{}", line).unwrap();
}
}
fn get_date(line: &str) -> &str {
let begin = line.find("[");
if begin.is_none() {
return &line[0..0];
}
let begin_pos = begin.unwrap();
let end = line[begin_pos+1..].find("]");
if end.is_none() {
return &line[0..0];
}
let end_pos = end.unwrap() + 1;
let date = &line[begin_pos+1 .. begin_pos+end_pos];
return date;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment