grep.rs(檔案已創建)
| @@ -0,0 +1,41 @@ | |||
| 1 | + | use anyhow::Result; | |
| 2 | + | use colored::*; | |
| 3 | + | use regex::Regex; | |
| 4 | + | use walkdir::WalkDir; | |
| 5 | + | ||
| 6 | + | pub fn ejecutar(patron: &str, ignorar_mayusculas: bool, archivo: &str) -> Result<()> { | |
| 7 | + | let re = if ignorar_mayusculas { | |
| 8 | + | Regex::new(&format!("(?i){}", patron))? | |
| 9 | + | } else { | |
| 10 | + | Regex::new(patron)? | |
| 11 | + | }; | |
| 12 | + | ||
| 13 | + | let path = std::path::Path::new(archivo); | |
| 14 | + | ||
| 15 | + | if path.is_dir() { | |
| 16 | + | for entry in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) { | |
| 17 | + | if entry.file_type().is_file() { | |
| 18 | + | buscar_en_archivo(&entry.path().to_string_lossy(), &re)?; | |
| 19 | + | } | |
| 20 | + | } | |
| 21 | + | } else { | |
| 22 | + | buscar_en_archivo(archivo, &re)?; | |
| 23 | + | } | |
| 24 | + | ||
| 25 | + | Ok(()) | |
| 26 | + | } | |
| 27 | + | ||
| 28 | + | fn buscar_en_archivo(ruta: &str, re: &Regex) -> Result<()> { | |
| 29 | + | let contenido = match std::fs::read_to_string(ruta) { | |
| 30 | + | Ok(c) => c, | |
| 31 | + | Err(_) => return Ok(()), | |
| 32 | + | }; | |
| 33 | + | ||
| 34 | + | for (num, linea) in contenido.lines().enumerate() { | |
| 35 | + | if re.is_match(linea) { | |
| 36 | + | println!("{}:{}: {}", ruta.cyan().bold(), (num + 1).to_string().yellow(), linea); | |
| 37 | + | } | |
| 38 | + | } | |
| 39 | + | ||
| 40 | + | Ok(()) | |
| 41 | + | } | |
上一頁
下一頁