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.
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.
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.
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.
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.
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With