Rename Files with Regex and directory_iterator
Learn to rename files with regex and directory_iterator.
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
formatter
specialization forpath
objects:
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 ...