grep.rs
· 1.0 KiB · Rust
Ham
use anyhow::Result;
use colored::*;
use regex::Regex;
use walkdir::WalkDir;
pub fn ejecutar(patron: &str, ignorar_mayusculas: bool, archivo: &str) -> Result<()> {
let re = if ignorar_mayusculas {
Regex::new(&format!("(?i){}", patron))?
} else {
Regex::new(patron)?
};
let path = std::path::Path::new(archivo);
if path.is_dir() {
for entry in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {
if entry.file_type().is_file() {
buscar_en_archivo(&entry.path().to_string_lossy(), &re)?;
}
}
} else {
buscar_en_archivo(archivo, &re)?;
}
Ok(())
}
fn buscar_en_archivo(ruta: &str, re: &Regex) -> Result<()> {
let contenido = match std::fs::read_to_string(ruta) {
Ok(c) => c,
Err(_) => return Ok(()),
};
for (num, linea) in contenido.lines().enumerate() {
if re.is_match(linea) {
println!("{}:{}: {}", ruta.cyan().bold(), (num + 1).to_string().yellow(), linea);
}
}
Ok(())
}
| 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 | } |