[英]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 : 下面是场景:
/X
at a regular interval of 5 minutes or when a log file size becomes 5MB /X
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.