Rename Files with Regex and directory_iterator
Explore how to use C++20 STL filesystem features to rename files in a directory with regular expressions. Understand directory_iterator and regex_replace to automate filename changes, handle multiple replacements, and avoid duplicates.
We'll cover the following...
We'll cover the following...
This is a simple utility that renames files using regular expressions. It uses directory_iterator to find the files in a directory and fs::rename() to rename them.
How to do it
In this recipe, we create a file rename utility that uses regular expressions:
We start by defining a few convenience aliases:
namespace fs = std::filesystem;using dit = fs::directory_iterator;using pat_v = vector<std::pair<regex, string>>;
The pat_v alias is a vector for use with our regular expressions.
We also continue to use the
formatterspecialization forpathobjects:
template<>struct std::formatter<fs::path>: std::formatter<std::string> {template<typename FormatContext>auto format(const fs::path& p, FormatContext& ctx) {return format_to(ctx.out(), "{}", p.string());}};
We have a function for applying the regular expression replacement to filename strings:
string replace_str(string s, const pat_v& replacements) {for(const auto& [pattern, repl] : replacements) {s = regex_replace(s, pattern, repl);}return s;}
...