Use A RegEx To Find And Replace In Multiple Files With Rust
July 2023
Haven't had a chance to write this up yet, but this is the snippet I use.
useregex::Captures;useregex::Regex;usestd::fs;usewalkdir::{Error, WalkDir};fnmain(){println!("Updating files...");update_files("/Users/alan/Desktop/sample").unwrap();}fnupdate_files(dir:&str)->Result<(), Error>{for entry inWalkDir::new(dir){let file_path = entry?.path().to_path_buf();ifletSome(ext)= file_path.extension(){match ext.to_str(){// SET THE FILE EXTENSION HERE
Some("txt")=>{println!("Updating: {}",&file_path.display());let data =fs::read_to_string(&file_path).unwrap();// SET THE FIND STRING HERE:
let re =Regex::new(r"br(ow)n").unwrap();let result = re.replace(data.as_str(),|caps:&Captures|{// SET THE REPALCE HERE:
format!("-- {} --",&caps[1].to_lowercase())});let_=fs::write(file_path, result.into_owned()).unwrap();}_=>{}}}}Ok(())}