Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

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.

Code

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(())
}