Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix FIND command in Groovy

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.

like image 215
Steve Avatar asked Dec 21 '12 20:12

Steve


People also ask

How do I run a Unix command in Groovy?

Executing shell commands using Groovy is very easy. For example If you want to execute any unix/linux command using groovy that can be done using execute() method and to see the output of the executed command we can append text after it.

What is the command to find a file in Unix?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in.

How do I find a directory in Unix?

The ls command is used to list files or directories in Linux and other Unix-based operating systems. Just like you navigate in your File explorer or Finder with a GUI, the ls command allows you to list all files or directories in the current directory by default, and further interact with them via the command line.

What does the command find do?

The find command is used to search and locate the list of files and directories based on conditions you specify for files that match the arguments. find command can be used in a variety of conditions like you can find files by permissions, users, groups, file types, date, size, and other possible criteria.


1 Answers

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
        }
    }
}
like image 84
ataylor Avatar answered Sep 29 '22 01:09

ataylor