5

I am working on converting a KornShell (ksh) script to Groovy. I have the following Find command - what would be a Groovy way to do something similar, without relying on Unix commands (I need this to work cross-platform, so I can not do a "blah blah".execute()).

find <source directory> -name <file pattern> -type f -mtime +140 -level 0

This code searches for all files in the source directory (no subdirs) that match a file pattern and are older than 140 days.

javaPlease42
  • 4,699
  • 7
  • 36
  • 65
Steve
  • 4,457
  • 12
  • 48
  • 89

1 Answers1

6

Groovy provides some methods for searching through directories: File.eachFile for the -level 0 case, or File.eachFileRecurse for the general case. Example:

use(groovy.time.TimeCategory) {
    new File(".").eachFile { file ->
        if (file.isFile() &&
            file.lastModified() < (new Date() - 140.days).time) {
            println file
        }
    }
}
ataylor
  • 64,891
  • 24
  • 161
  • 189
  • 2
    or if you're doing level 0, you could do File.listFiles() and follow that with findAll to just get the old files into a collection – tim_yates Dec 21 '12 at 20:49
  • 1
    The asker also wanted to match name against a pattern which needs to use eachFileMatch() such as new File('.').eachFileMatch(~/.*?\.JPG/) {... – CodeMonkey Dec 22 '12 at 00:45