From 8da6c9cfd26fcbaebd50ff1b9ab3dd26ea584e05 Mon Sep 17 00:00:00 2001 From: JIe Date: Wed, 20 Nov 2024 13:41:42 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=8C=89=E5=85=B3=E9=94=AE?= =?UTF-8?q?=E5=AD=97=E7=AD=9B=E9=80=89=E5=8A=9F=E8=83=BD(=E8=A1=8C)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cli.rs | 4 ++++ src/main.rs | 25 +++++++++++++++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 5344654..1d70065 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -23,6 +23,10 @@ pub struct App { #[arg(short, long, conflicts_with = "delimiter")] pub tsv: bool, + ///Filter str, will select line contains this str; + #[arg(short, long, default_value = "")] + pub filter_str: String, + /// Specify the field delimiter. #[arg(short, long, default_value_t = ',')] pub delimiter: char, diff --git a/src/main.rs b/src/main.rs index 8251e18..3e38311 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,7 +8,7 @@ use cli::App; use csv::{ErrorKind, ReaderBuilder}; use std::{ fs::File, - io::{self, BufWriter, IsTerminal, Read}, + io::{self, BufRead, BufReader, BufWriter, Cursor, IsTerminal, Read}, process, }; use table::TablePrinter; @@ -65,6 +65,7 @@ fn try_main() -> anyhow::Result<()> { number, tsv, delimiter, + filter_str, style, padding, indent, @@ -90,7 +91,27 @@ fn try_main() -> anyhow::Result<()> { .delimiter(if tsv { b'\t' } else { delimiter as u8 }) .has_headers(!no_headers) .from_reader(match file { - Some(path) => Box::new(File::open(path)?) as Box, + Some(path) => { + let data = Box::new(File::open(path)?) as Box; + if filter_str == "" { + data + } else { + let reader = BufReader::new(data); + let filter_data: Vec = reader + .lines() + .filter_map(|line| { + let line = line.unwrap(); + if line.contains(&filter_str) { + Some(line) + } else { + None + } + }) + .flat_map(|str| str.into_bytes()) + .collect(); + Box::new(Cursor::new(filter_data)) as Box + } + } None if io::stdin().is_terminal() => bail!("no input file specified (use -h for help)"), None => Box::new(io::stdin()), });