Searching through files is one of the most common tasks for command-line utilities. Whether you're looking for a specific word in a file, counting occurrences, or filtering by file types, Rust’s performance makes it a great choice for creating fast and efficient search tools. In this article, we’ll walk through building a CLI tool in Rust that searches through a file and counts the occurrences of a specific word.
Step 1: Set Up Your Project
Create a new Rust project:
cargo new file_searcher --bin
cd file_searcher
This initializes a basic project with src/main.rs
.
Step 2: Add Dependencies
We’ll use the regex
crate to search for patterns within text. Add it to your Cargo.toml
file:
[dependencies]
regex = "1.0"
This crate allows us to search for regex patterns, which will be useful for matching specific words or phrases within the files.
Step 3: Implement the Search Functionality
Now, let’s write the logic to open a file, search for a word, and count its occurrences. Here’s the code for main.rs
:
use regex::Regex;
use std::env;
use std::fs::File;
use std::io::{self, BufRead};
use std::process;
fn search_file(filename: &str, search_term: &str) -> Result {
let file = File::open(filename)?;
let reader = io::BufReader::new(file);
let regex = Regex::new(search_term).unwrap();
let mut count = 0;
for line in reader.lines() {
let line = line?;
if regex.is_match(&line) {
count += 1;
}
}
Ok(count)
}
fn main() {
let args: Vec = env::args().collect();
if args.len() < 3 {
eprintln!("Usage: file_searcher ");
process::exit(1);
}
let filename = &args[1];
let search_term = &args[2];
match search_file(filename, search_term) {
Ok(count) => println!("Found '{}' {} times", search_term, count),
Err(e) => {
eprintln!("Error reading file: {}", e);
process::exit(1);
}
}
}
Step 4: Build and Test
Build the project:
cargo build --release
Run the tool to search for a word in a file:
./target/release/file_searcher sample.txt "Rust"
If the word "Rust" appears in the file, the tool will output the number of times it was found.
Use Case Scenario
Imagine you’re working with a collection of log files and need to search for error messages. Using a CLI tool like this allows you to automate the process, providing quick insights into logs without having to manually open each file. You could extend this tool to support multiple search terms, case-insensitive searching, or even search across directories, making it more flexible for various use cases like log analysis or data extraction.
✅ Pros and ❌ Cons of Using Rust for CLI Tools
✅ Pros:
- ⚡ Extremely fast and efficient for large files
- 🔍 Powerful regex support for advanced search functionality
- 🧼 Memory safety guarantees to prevent common bugs
- 🧪 Great testability, allowing for robust unit tests
❌ Cons:
- 📘 May have a steep learning curve for beginners
- ⏱ Compilation times can be slow on larger projects
- 🧱 Limited third-party libraries compared to more mature ecosystems
Summary
You’ve now built a simple but powerful file searcher in Rust! By using regex
and the Rust standard library, you can create a fast, safe, and reliable utility for searching through files. This tool can be extended to support various search features and applied to a wide range of tasks.
Want to dive deeper into building your own Rust-based CLI tools? My 15-page guide walks you through building fast, reliable utilities with Rust from scratch:
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)