Managing files and directories is a task that many developers and system administrators face regularly. Renaming files in batches can be a tedious process when done manually. In this tutorial, we’ll build a Rust CLI tool that allows you to rename multiple files in a directory according to a specified pattern, saving time and effort.
Step 1: Set Up Your Project
Let’s begin by creating a new Rust project:
cargo new file_renamer --bin
cd file_renamer
This initializes a new Rust project with a src/main.rs
file, where we’ll write the logic for our tool.
Step 2: Add Dependencies
We will use the walkdir
crate to traverse directories and the std::fs
module for file renaming. Add walkdir
to your Cargo.toml
:
[dependencies]
walkdir = "2.3"
This crate will help us iterate through all files in a directory, including files in subdirectories.
Step 3: Implement the File Renaming Logic
We’ll now write the code to rename all files in a specified directory based on a pattern. The tool will take a directory path and a name pattern, and it will rename all files in the directory according to the pattern.
Here’s the code for main.rs
:
use std::env;
use std::fs;
use std::path::Path;
use std::process;
use walkdir::WalkDir;
fn rename_files_in_directory(directory: &str, pattern: &str) -> Result<(), Box> {
for entry in WalkDir::new(directory).into_iter().filter_map(|e| e.ok()) {
if entry.metadata()?.is_file() {
let old_name = entry.path().display().to_string();
let new_name = old_name.replace("old", pattern);
fs::rename(&old_name, &new_name)?;
println!("Renamed: {} -> {}", old_name, new_name);
}
}
Ok(())
}
fn main() {
let args: Vec = env::args().collect();
if args.len() < 3 {
eprintln!("Usage: file_renamer ");
process::exit(1);
}
let directory = &args[1];
let pattern = &args[2];
if let Err(e) = rename_files_in_directory(directory, pattern) {
eprintln!("Error renaming files: {}", e);
process::exit(1);
}
}
Step 4: Build and Test the Tool
Now, build and run the tool. For example, if you have a directory with files like old_file1.txt
, old_file2.txt
, and so on, you can rename them by running:
cargo build --release
./target/release/file_renamer ./path/to/your/files new
This will rename all files by replacing the word "old" with "new". If successful, the output will show the renamed files:
Renamed: old_file1.txt -> new_file1.txt
Renamed: old_file2.txt -> new_file2.txt
Use Case Scenario
This tool can be useful in cases where you need to rename multiple files in bulk, such as in a batch of image files, logs, or project files. For instance, you may need to standardize the names of files in a directory before uploading them to a server or renaming files in a media library. This Rust CLI tool allows for quick and easy batch file renaming, saving time compared to manual renaming.
✅ Pros and ❌ Cons of Using Rust for CLI Tools
✅ Pros:
- ⚡ Rust is fast and efficient, making it perfect for handling bulk file operations.
- 🧑💻 Rust's error handling system helps ensure your tool is robust and reliable.
- 🔄 The tool is flexible, and you can easily modify it to meet specific renaming rules or patterns.
- 🧪 Rust’s testing and documentation systems make it easy to maintain and extend.
❌ Cons:
- 📘 Rust may have a steep learning curve for those new to the language.
- 🔄 Limited third-party libraries compared to languages like Python or JavaScript.
- ⏱ Compilation times may be slower for large projects.
Summary
In this tutorial, we built a Rust CLI tool to rename files in a directory based on a pattern. We used the walkdir
crate to traverse the directory and the std::fs
module to rename files. This tool is fast, reliable, and flexible, allowing you to automate the renaming process for large batches of files.
To take your Rust CLI skills even further, check out my 15-page PDF guide, which walks you through crafting high-performance command-line tools:
Crafting Command-Line Tools in Rust: A Practical Guide to Building Fast, Reliable Utilities — just $5.
If this was helpful, you can also support me here: Buy Me a Coffee ☕
Top comments (0)