Home

Use A RegEx To Find And Replace In Multiple Files With Rust

Haven't had a chance to write this up yet, but this is the snippet I use.

rust
use regex::Captures;
use regex::Regex;
use std::fs;
use walkdir::{Error, WalkDir};

fn main() {
    println!("Updating files...");
    update_files("/Users/alan/Desktop/sample").unwrap();
}

fn update_files(dir: &str) -> Result<(), Error> {
    for entry in WalkDir::new(dir) {
        let file_path = entry?.path().to_path_buf();
        if let Some(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(())
}

- needs cargo add walkdir

- needs cargo add regex

~ fin ~