'Glob Multiple File Types
I want to find files for some pattern with multiple extensions. Ex:-
some/path/**.{json,jsonc}
But rust glob function is not working with these types of patterns. Here is my workaround:-
extern crate glob;
use glob::glob;
fn main() {
for file_name_result in glob("example/**.{json,jsonc}").unwrap() {
match file_name_result {
Ok(file_path) => {
println!("Found:{}", file_path.display());
}
Err(e) => {
eprintln!("ERROR: {}", e);
}
};
}
}
Solution 1:[1]
You're right, glob
doesn't accept this kind of pattern. You need to call it once for each extension:
extern crate glob;
use glob::glob;
fn main() {
for file_name_result in glob("example/**/*.json")
.unwrap()
.chain(glob("example/**/*.jsonc").unwrap())
{
match file_name_result {
Ok(file_path) => {
println!("Found:{}", file_path.display());
}
Err(e) => {
eprintln!("ERROR: {}", e);
}
};
}
}
Solution 2:[2]
For those looking for more advanced use cases of glob, there is also the globwalk library which handles multiple extensions and exclusions.
example/**.{json,jsonc}
Here is a code snippet from their documentation.
extern crate globwalk;
use std::fs;
let walker = globwalk::GlobWalkerBuilder::from_patterns(
BASE_DIR,
&["*.{png,jpg,gif}", "!Pictures/*"],
)
.max_depth(4)
.follow_links(true)
.build()?
.into_iter()
.filter_map(Result::ok);
for img in walker {
fs::remove_file(img.path())?;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ömer Erden |
Solution 2 | DTDynasty |