Batch renaming files with regex in Rust

Renaming a folder of files by hand (IMG_0001.jpg to holiday_0001.jpg, stripping a prefix, swapping date formats) is tedious. This post builds a small command-line tool that does it with a regular expression: it matches each file name against a pattern and replaces the match with a replacement string that can reuse capture groups.
It uses Rust’s standard library for file operations, the regex crate for matching, and clap for argument parsing.
Setting up the project
Section titled “Setting up the project”cargo new file_renamercd file_renamercargo add clap --features derivecargo add regexCargo.toml ends up roughly like this (versions current as of November 2026; edition 2024 needs Rust 1.85 or later):
[package]name = "file_renamer"version = "0.1.0"edition = "2024"
[dependencies]clap = { version = "4.6", features = ["derive"] }regex = "1.13"The code
Section titled “The code”Everything fits in src/main.rs:
use clap::Parser;use regex::Regex;use std::error::Error;use std::fs;use std::io;use std::path::{Path, PathBuf};
/// Batch rename files in a directory using a regex#[derive(Parser)]#[command(version, about)]struct Args { /// Directory containing the files to rename directory: PathBuf,
/// Regex matched against each file name pattern: String,
/// Replacement text; can use capture groups like $1 or ${name} #[arg(default_value = "")] replacement: String,
/// Print the planned renames without changing anything #[arg(long)] dry_run: bool,}
fn rename_files(dir: &Path, re: &Regex, replacement: &str, dry_run: bool) -> io::Result<()> { for entry in fs::read_dir(dir)? { let path = entry?.path(); if !path.is_file() { continue; }
// Skip names that aren't valid UTF-8 instead of panicking. let Some(name) = path.file_name().and_then(|n| n.to_str()) else { continue; };
let new_name = re.replace_all(name, replacement); if new_name == name || new_name.is_empty() { continue; }
let new_path = path.with_file_name(&*new_name); if new_path.exists() { eprintln!("skipping {name}: {} already exists", new_path.display()); continue; }
println!("{name} -> {new_name}"); if !dry_run { fs::rename(&path, &new_path)?; } } Ok(())}
fn main() -> Result<(), Box<dyn Error>> { let args = Args::parse(); let re = Regex::new(&args.pattern)?; rename_files(&args.directory, &re, &args.replacement, args.dry_run)?; Ok(())}How it works:
#[derive(Parser)]generates the argument parser from theArgsstruct. Doc comments become the--helptext, and#[command(version, about)]pulls the version fromCargo.tomland the description from the struct’s doc comment.Regex::newcompiles the pattern once. An invalid pattern returns an error frommaininstead of panicking.replace_allreturns aCow<str>: it only allocates when something matched, so unchanged names are cheap to skip.- The tool refuses to overwrite an existing file and skips names that end up empty.
fs::renamewould otherwise silently replace an existing file with the same name. --dry-runprints the plan without touching the disk. Run it first.
The replacement defaults to an empty string, so with only a pattern the tool deletes whatever matches.
Using it
Section titled “Using it”Preview renaming IMG_0001.jpg to holiday_0001.jpg:
cargo run -- ./photos 'IMG_(\d+)' 'holiday_$1' --dry-runDrop --dry-run to apply it. Strip a (copy) suffix from every file:
cargo run -- ./docs ' \(copy\)'Use single quotes so your shell doesn’t expand $1 itself.
Gotchas
Section titled “Gotchas”$1followed by letters, digits or_. Theregexcrate reads$1_oldas a group named1_old, which doesn’t exist, so it expands to nothing. Write${1}_oldinstead.- Case-only renames. On case-insensitive filesystems (the Windows and macOS defaults),
Report.txttoreport.txtlooks like the target already exists, so the tool skips it. - Not recursive.
fs::read_dironly lists the top level. For subdirectories, use thewalkdircrate. - Anchor your patterns.
\d+matches anywhere in the name, including the extension. Use^and$(for example^IMG_(\d+)\.jpg$) when you mean the whole name.
Further reading
Section titled “Further reading”© 2026 David Li · Home · Blog · RSS ·Classic site · Built with Astro, Starlight and three.js · Logos:Font Awesome Free (CC BY 4.0)