添加按关键字筛选功能(行)
This commit is contained in:
parent
1c8e2579b9
commit
8da6c9cfd2
@ -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,
|
||||
|
25
src/main.rs
25
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<dyn Read>,
|
||||
Some(path) => {
|
||||
let data = Box::new(File::open(path)?) as Box<dyn Read>;
|
||||
if filter_str == "" {
|
||||
data
|
||||
} else {
|
||||
let reader = BufReader::new(data);
|
||||
let filter_data: Vec<u8> = 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<dyn Read>
|
||||
}
|
||||
}
|
||||
None if io::stdin().is_terminal() => bail!("no input file specified (use -h for help)"),
|
||||
None => Box::new(io::stdin()),
|
||||
});
|
||||
|
Loading…
Reference in New Issue
Block a user