简体   繁体   English

如何从目录中查找最新文件

[英]How to find most recent file from a directory

I want to parse a log file which is in /X on a Linux server. 我想解析Linux服务器上/X的日志文件。 Below is the scenario : 下面是场景:

  • Log files are pushed into /X at a regular interval of 5 minutes or when a log file size becomes 5MB 日志文件每隔5分钟或当日志文件大小变为5MB时被推入/X
  • Now we are trying to make a parser which parses the latest created log file and gets the required information 现在,我们尝试制作一个解析器,用于解析最新创建的日志文件并获取所需的信息

How can I retrieve the file name of the most recent log file? 如何检索最新日志文件的文件名?

#!/bin/bash

dir=/X
for file in "${dir}"/*; do
    [ -f "${file}" ] || continue
    [ "${file}" -nt "${newest}" ] && newest=${file}
done

echo "the most recentently modified file is '${newest}'"

Hi Abhinav if you only want to get file name you can use ls -Art | 您好Abhinav如果您只想获取文件名,可以使用ls -Art | tail -n 1 command in your script. 脚本中的tail -n 1命令。

ls -t will sort files by modification time (in your case it's the same as creation time, since the files are written once), and head -1 will give the first file, ie the most recent: ls -t将按修改时间对文件进行排序(在您的情况下,它与创建时间相同,因为文件被写入一次),而head -1将给出第一个文件,即最新的文件:

ls -t /X | head -1

A slight variation, which I think is more common, is listing in reverse ( -r ) and using tail : 我认为较常见的一个细微变化是反向列出( -r )并使用tail

ls -rt /X | tail -1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM