Groovy 读取目录中的最新文件

发布于 2024-10-02 04:43:26 字数 1048 浏览 0 评论 0原文

我只是有一个关于编写一个函数的问题,该函数将在目录中搜索目录中的最新日志。我目前想出了一个,但我想知道是否有更好(也许更合适)的方法来做到这一点。

我目前正在使用 hdsentinel 在计算机上创建日志并将日志放置在目录中。日志的保存方式如下:

/directory/hdsentinel-computername-date

ie. C:/hdsentinel-owner-2010-11-11.txt

因此,我编写了一个快速脚本,该脚本循环访问某些变量以检查最近的变量(过去一周内),但在查看它之后,我怀疑这样做的效率和正确性如何方式。

这是脚本:

String directoryPath = "D:"
def computerName = InetAddress.getLocalHost().hostName
def dateToday = new Date()
def dateToString = String.format('%tm-%<td-%<tY', dateToday)
def fileExtension = ".txt"
def theFile


for(int i = 0; i < 7; i++) {
    dateToString = String.format('%tY-%<tm-%<td', dateToday.minus(i))
    fileName = "$directoryPath\\hdsentinel-$computerName-$dateToString$fileExtension"

    theFile = new File(fileName)

    if(theFile.exists()) {
        println fileName
        break;
    } else {
        println "Couldn't find the file: " + fileName
    }
}

theFile.eachLine { print it }

该脚本工作正常,也许有一些缺陷。我觉得我应该在继续之前询问此类事情的典型路线是什么。

感谢所有的意见。

I just have a question about writing a function that will search a directory for the most recent log in a directory. I currently came up with one, but I'm wondering if there is a better (perhaps more proper) way of doing this.

I'm currently using hdsentinel to create logs on computer and placing the log in a directory. The logs are saved like so:

/directory/hdsentinel-computername-date

ie. C:/hdsentinel-owner-2010-11-11.txt

So I wrote a quick script that loops through certain variables to check for the most recent (within the past week) but after looking at it, I'm question how efficient and proper it is to do things this way.

Here is the script:

String directoryPath = "D:"
def computerName = InetAddress.getLocalHost().hostName
def dateToday = new Date()
def dateToString = String.format('%tm-%<td-%<tY', dateToday)
def fileExtension = ".txt"
def theFile


for(int i = 0; i < 7; i++) {
    dateToString = String.format('%tY-%<tm-%<td', dateToday.minus(i))
    fileName = "$directoryPath\\hdsentinel-$computerName-$dateToString$fileExtension"

    theFile = new File(fileName)

    if(theFile.exists()) {
        println fileName
        break;
    } else {
        println "Couldn't find the file: " + fileName
    }
}

theFile.eachLine { print it }

The script works fine, perhaps it has some flaws. I felt I should go ahead and ask what the typical route is for this type of thing before I continue with it.

All input is appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情愿 2024-10-09 04:43:26

虽然有点混乱,但您可以通过“groupBy”方法实现多列排序(阐述 Aaron 的代码)。

def today = new Date()
def recent = {file -> today - new Date(file.lastModified()) < 7}

new File('/yourDirectory/').listFiles().toList()
.findAll(recent)
.groupBy{it.name.split('-')[1]}
.collect{owner, logs -> logs.sort{a,b -> a.lastModified() <=> b.lastModified()} }
.flatten()
.each{ println "${new Date(it.lastModified())}  ${it.name}" } 

这会找到上周创建的所有日志,按所有者名称对它们进行分组,然后根据修改日期进行排序。

如果目录中还有日志以外的文件,则可能首先需要 grep 查找包含“hdsentinel”的文件。

我希望这有帮助。

编辑:
从您提供的示例中,我无法确定格式中的最低有效数字是否为:

C:/hdsentinel-owner-2010-11-11.txt

代表月份或日期。如果是后者,按文件名排序将自动按所有者排序,然后按创建日期排序(没有上述代码的所有欺骗行为)。

例如:

new File('/directory').listFiles().toList().findAll(recent).sort{it.name}

Though a bit messy, you could implement a multi-column sort via the 'groupBy' method (Expounding on Aaron's code)..

def today = new Date()
def recent = {file -> today - new Date(file.lastModified()) < 7}

new File('/yourDirectory/').listFiles().toList()
.findAll(recent)
.groupBy{it.name.split('-')[1]}
.collect{owner, logs -> logs.sort{a,b -> a.lastModified() <=> b.lastModified()} }
.flatten()
.each{ println "${new Date(it.lastModified())}  ${it.name}" } 

This finds all logs created within the last week, groups them by owner name, and then sorts according to date modified.

If you have files other than logs in the directory, you may first need to grep for files containing 'hdsentinel.'

I hope this helps.

EDIT:
From the example you provided, I cannot determine if the least significant digit in the format:

C:/hdsentinel-owner-2010-11-11.txt

represents the month or the day. If the latter, sorting by file name would automatically prioritize by owner, and then by date created (without all of the chicanery of the above code).

For Instance:

new File('/directory').listFiles().toList().findAll(recent).sort{it.name}
漫漫岁月 2024-10-09 04:43:26

希望这对一些人有帮助......这以更常规的方式按修改日期对给定路径进行排序。列出了它们。

您可以限制列表,并在闭包中添加其他条件以获得所需的结果

 new File('/').listFiles().sort() {
   a,b -> a.lastModified().compareTo b.lastModified()
 }.each {
     println  it.lastModified() + "  " + it.name
 } 

Hopefully this helps some..This sorts a given path by date modified in a groovier way. The lists them out.

you can limit the list, and add other conditions in the closure to get the desired results

 new File('/').listFiles().sort() {
   a,b -> a.lastModified().compareTo b.lastModified()
 }.each {
     println  it.lastModified() + "  " + it.name
 } 
☆獨立☆ 2024-10-09 04:43:26

当我试图解决类似的问题时,学习了一种更简洁的方法。

定义一个用于排序的闭包

def fileSortCondition = { it.lastModified() }

File.listFiles() 还有其他变体,它接受 Java 中的 FileFilter 和 FilenameFilter,并且这些接口有一个名为accept的方法,将接口实现为闭包。

def fileNameFilter = { dir, filename ->
if(filename.matches(regrx))
    return true
else
    return false
} as FilenameFilter

最后,

new File("C:\\Log_Dir").listFiles(fileNameFilter).sort(fileSortCondition).reverse()

如果要通过文件属性完成过滤,请实现 FileFilter 接口。

def fileFilter = {  file ->
        if(file.isDirectory())
             return false 
        else
            return true }  as FileFilter

As I was trying to solve a similar problem, learnt a much cleaner approach.

Define a closure for sorting

def fileSortCondition = { it.lastModified() }

And File.listFiles() has other variation which accepts FileFilter and FilenameFilter in Java, and these interfaces has a single method called accept, Implement the interface as a closure.

def fileNameFilter = { dir, filename ->
if(filename.matches(regrx))
    return true
else
    return false
} as FilenameFilter

And lastly

new File("C:\\Log_Dir").listFiles(fileNameFilter).sort(fileSortCondition).reverse()

Implement FileFilter interface if filtering is to be done by File attributes.

def fileFilter = {  file ->
        if(file.isDirectory())
             return false 
        else
            return true }  as FileFilter
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文