0

I have two directories which have some files since 20019.
Now I need to make a glob which collects only the files from the last 6 months.

I have tried to use this functions but I haven't found a way to get the sequence for the month and year from month X to current Month via year change.

logger.info("getYear {}", LocalDate.now().minusMonths(6).getYear());
logger.info("last 6 month log7177/log-{}-{}", 
      LocalDate.now().minusMonths(6).getYear(),
      LocalDate.now().minusMonths(6).getMonthValue());

the Shell pattern looks like this

ls -la log7177/log-2022-{09,10,11}* log7177/log-2023-{01,02,03}*

Any hint into the right direction is really appreciated.

Aleksandar
  • 2,442
  • 3
  • 15
  • 24

1 Answers1

0

Based on this Java 8 LocalDate - How do I get all dates between two dates? answer have I created this code

List<String> dirs = Arrays.asList("dir1", "dir2");
StringBuffer toGlobFiles = new StringBuffer("*{");
LocalDate ldStart = LocalDate.now().minusMonths(6);

List<LocalDate> dates = ldStart // Determine your beginning `LocalDate` object.
        .datesUntil( // Generate stream of `LocalDate` objects.
                ldStart.plusMonths(7), Period.ofMonths(1) // Calculate your ending date, and ask for a stream of
                                                              // dates till then.
        ) // Returns the stream.
        .collect(Collectors.toList()); // Collect your resulting dates in a `List`.

for (LocalDate localDate : dates) {
  logger.info("{}",localDate.format(DateTimeFormatter.ofPattern("YYYY-MM,")));
  toGlobFiles.append(localDate.format(DateTimeFormatter.ofPattern("YYYY-MM,")));
}

// Remove last ',' from the loop above
toGlobFiles.setLength(toGlobFiles.length() - 1);
toGlobFiles.append("}*.{gz,log}");

logger.info("toGlobFiles {}", toGlobFiles);

for (String dir : dirs) {
    Files.newDirectoryStream(Paths.get(dir), toGlobFiles.toString()).forEach(files::add);
}

logger.info("Found # of files {}", files.size());

The output of the run is this.

toGlobFiles *{2022-09,2022-10,2022-11,2022-12,2023-01,2023-02,2023-03}*.{gz,log}
Found # of files 352
Aleksandar
  • 2,442
  • 3
  • 15
  • 24