• Custer
    2021-10-15
    1. 最简单的 ```rust use std::error::Error; use clap::{AppSettings, Clap}; use colored::Colorize; use tokio::fs; #[derive(Clap)] #[clap(version = "1.0", author = "Custer<custer@email.cn>")] #[clap(setting = AppSettings::ColoredHelp)] struct Opts { find: String, path: String, } #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { // 1. 解析参数 let opts: Opts = Opts::parse(); let find = opts.find; let path = opts.path; let length = find.len(); // 2. 读取文件 let contents = fs::read_to_string(path).await?; // 3. 匹配字符串 for (row, line) in contents.lines().enumerate() { if let Some(col) = line.find(&find) { println!( "{}:{} {}{}{}", row + 1, col + 1, &line[..col], &line[col..col + length].red().bold(), &line[col + length..] ); } } Ok(()) } ``` 2. 允许用户提供一个正则表达式,来查找文件中所有包含该字符串的行 ```rust // 3. 匹配字符串 for (row, line) in contents.lines().enumerate() { if let Some(re) = Regex::new(find.as_str()).unwrap().find(line) { let start = re.start(); let end = re.end(); println!( "{}:{} {}{}{}", row + 1, start + 1, &line[..start], &line[start..end].red().bold(), &line[end..] ); } } ``` 3. 允许用户提供一个正则表达式,来查找满足文件通配符的所有文件(好像并不需要使用globset 或者 glob 就可以处理通配符?) ```rust ... struct Opts { find: String, #[clap(multiple_values = true)] paths: Vec<String>, } #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { // 1. 解析参数 let opts: Opts = Opts::parse(); let find = opts.find.as_str(); let paths = opts.paths; // 2. 循环读取匹配到的文件 for path in paths { println!("{:?}", path); let contents = fs::read_to_string(path).await?; // 3. 匹配字符串 ... } Ok(()) } ```
    展开

    作者回复: 👍 非常好!

    
    3
  • 余泽锋
    2021-10-17
    时间比较紧,先写个初始版本: extern crate clap; use std::path::Path; use std::ffi::OsStr; use std::error::Error; use clap::{Arg, App}; use regex::Regex; use tokio::fs::{File, read_dir}; use tokio::io::AsyncReadExt; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { let matches = App::new("rgrep") .version("1.0") .about("Does awesome things") .arg(Arg::with_name("key_word") .index(1)) .arg(Arg::with_name("file") .multiple(true) .index(2)) .get_matches(); println!("{:?}", matches); let key_word = matches.value_of("key_word").unwrap(); println!("{}", key_word); let file_path = matches.values_of_lossy("file").unwrap(); println!("{:?}", file_path); let re_key_word = format!(r"{}", &key_word); println!("re_key_word: {}", &re_key_word); let re = Regex::new(&re_key_word).unwrap(); for file_path in file_path { let mut file = File::open(&file_path).await?; // let mut contents = vec![]; let result = tokio::fs::read_to_string(&file_path).await?; if let Some(caps) = re.captures(&result) { println!("file_path: {:?}", &file_path); println!("file: {:?}", &file); println!("caps: {:?}", &caps); println!("result: {:?}", &result); } } Ok(()) }
    展开

    作者回复: 嗯,不错。可以进一步优化一下性能以及可测试性。建议看看我的参考代码:https://github.com/tyrchen/geektime-rust/tree/master/mid_term_rgrep

    
    2
  • 夏洛克Moriaty
    2021-10-14
    磕磕盼盼搞了一天终于实现了这一讲的需求,期中测试算是通过了。自己动手实现的过程中收获了非常多的东西。代码结构前前后后改了许多次,还达不到开发过程中接口不变只是实现变的能力。我把代码仓库链接贴在下面算是献丑了,说实话有点不好意思拿出来哈哈。 https://github.com/LgnMs/rgrep

    作者回复: 挺不错的!流程图画的很好啊,可以放到 Readme.md 里

    
    2
  • D. D
    2021-10-15
    试着写了一下,实现得比较匆忙。 为了练习之前学过的内容,试了各种写法,应该会有很多不合理的地方。 而且没有做并行化,希望以后有时间可以加上,并把代码重构得更好。 https://github.com/imag1ne/grepr

    作者回复: 嗯,写的很不错,尤其是 Display trait 的使用。比我用一个函数处理更好。 impl Display for MatchLine<'_>

    
    1
  • 记事本
    2021-10-13
    let filename = std::env::args().nth(2).unwrap(); let query = std::env::args().nth(1).unwrap(); let case_sensitive = std::env::var("is_sens").is_err(); let contents = std::fs::read_to_string(filename).unwrap(); if case_sensitive { let mut i = 1; for v in contents.lines(){ if v.contains(&query){ println!("{}:{}",i,v); } i+=1; } }else { let c =contents.lines().filter(|item|item.contains(&query)).collect::<Vec<_>>(); for i in 1..=c.len(){ println!("{}:{}",i,c[i]); } }

    作者回复: 嗯,你可以用 regex 处理,更方便一些。你也可以看看 github 仓库里的代码:https://github.com/tyrchen/geektime-rust/tree/master/mid_term_rgrep

    
    1
  • forever 蒙
    2022-06-09
    error: The following required arguments were not provided: <PATTERN> <GLOB> USAGE: rgrep.exe <PATTERN> <GLOB> For more information try --help error: process didn't exit successfully: `E:\geektime-Rust-master\geektime-rust-master\target\debug\rgrep.exe` (exit code: 2) Process finished with exit code 2 求助。。。不知道为什么总输出这个
    
    
  • forever 蒙
    2022-06-08
    error: The following required arguments were not provided: <PATTERN> <GLOB> USAGE: rgrep.exe <PATTERN> <GLOB> For more information try --help error: process didn't exit successfully: `E:\geektime-Rust-master\geektime-rust-master\target\debug\rgrep.exe` (exit code: 2)求助
    
    
  • gt
    2022-03-19
    交个作业:https://github.com/ForInfinity/rgrep 把整个程序分成了fs、pattern、formatter三个部分,分别负责文件读写、匹配和高亮及输出console。先分别敲定了trait,然后实现。以后可以扩展使用不同的fs来源、更多的匹配模式、不同的formatter。 不过在编写泛型的时候遇到了个问题: 首先存在一个trait MatchOutput: ``` pub trait MatchOutput<T> where T: Display ``` 当我想实现另一个trait Printer时: `` pub struct Printer<M: Display, T: MatchOutput<M>> { pub formatter: T, } ``` rust会编译不通过,提示存在未使用的泛型M: ``` error[E0392]: parameter `M` is never used ``` 对此不太理解,也不知道是不是因为这不是最佳实践。 现在临时的解决方案是添加一个私有的变量_m:M,并在写new方法的时候将其初始化为None: ``` pub struct Printer<M: Display, T: MatchOutput<M>> { // To pass the compiler // Otherwise: error[E0392]: parameter `M` is never used _m: Option<M>, pub formatter: T, } ``` 蹲个老师的解答。
    展开
    
    
  • Geek_994f3b
    2022-03-08
    也写了个:https://github.com/startdusk/rgrep,欢迎老师指正
    
    