如何生成跨年度近6个月的文件Glob匹配日期序列?
解决方案
要生成跨年度的近6个月文件匹配glob模式,核心是先枚举近6个月的所有年月组合,再按年份分组生成匹配规则,以下是具体实现步骤和代码:
步骤说明
- 计算起始日期:取当前日期往前推6个月的当月第一天,避免日期差异导致漏算月份
- 遍历从起始月到当前月的所有月份,收集每个月的「年份-补零月份」组合
- 按年份分组,将同一年的月份整理成
{mm1,mm2,...}格式 - 拼接成最终的glob模式字符串
Java 代码实现
import java.time.LocalDate; import java.time.YearMonth; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class GlobPatternGenerator { public static void main(String[] args) { // 目录前缀 String dirPrefix = "log7177/log-"; // 获取近6个月的起始年月与当前年月 YearMonth startMonth = YearMonth.from(LocalDate.now().minusMonths(6)); YearMonth currentMonth = YearMonth.now(); // 生成从起始月到当前月的所有年月流 Stream<YearMonth> monthStream = Stream.iterate(startMonth, ym -> ym.plusMonths(1)) .limit(6); // 固定取6个月 // 按年份分组,收集每个年份下的补零月份列表 Map<Integer, List<String>> yearToMonths = monthStream .collect(Collectors.groupingBy( YearMonth::getYear, Collectors.mapping(ym -> String.format("%02d", ym.getMonthValue()), Collectors.toList()) )); // 拼接成最终的glob模式 List<String> globParts = yearToMonths.entrySet().stream() .map(entry -> { String year = entry.getKey().toString(); String months = String.join(",", entry.getValue()); return dirPrefix + year + "-{" + months + "}*"; }) .collect(Collectors.toList()); // 输出结果 String finalGlob = String.join(" ", globParts); System.out.println("生成的glob模式:"); System.out.println(finalGlob); // 示例输出:log7177/log-2022-{09,10,11}* log7177/log-2023-{01,02,03}* } }
关键细节说明
- 使用
YearMonth处理年月更精准,避免LocalDate的日期部分干扰,比如2023-03-31减6个月会到2022-09-30,但我们要的是2022-09整个月 String.format("%02d", month)确保月份是两位数字,比如9→09,匹配文件名的格式- 按年份分组后生成
{mm1,mm2,...}格式,完全符合shell glob的语法规则 - 最终拼接的字符串可以直接用于文件遍历,比如Java的
Files.newDirectoryStream,或生成shell命令
内容的提问来源于stack exchange,提问作者Aleksandar
相关产品推荐
相关产品推荐

