击功能查找最新的文件匹配的模式

问题描述:

在bash中,我想创建一个返回匹配特定模式的最新文件的文件名功能。例如,我有文件的目录,如:

In Bash, I would like to create a function that returns the filename of the newest file that matches a certain pattern. For example, I have a directory of files like:

Directory/
   a1.1_5_1
   a1.2_1_4
   b2.1_0
   b2.2_3_4
   b2.3_2_0

我要以'B2'开头的最新文件。我如何在bash这样做呢?我需要这在我的〜/ .bash_profile中脚本。

LS 命令有一个参数 -t 按时间排序。然后,您可以抢到第一(最新)头-1

The ls command has a parameter -t to sort by time. You can then grab the first (newest) with head -1.

ls -t b2* | head -1

但要注意:

  • Why you shouldn't parse the output of ls(1)
  • How can I find the latest (newest, earliest, oldest) file in a directory?

我个人的看法是:解析 LS 仅在危险的时候文件名包含有趣的字符,如换行或空格。如果你能保证文件名不包含奇怪的字符,然后解析 LS 是相当安全的。不过,如果你正在开发其目的是要通过很多人在许多不同的情况下,许多系统运行的脚本,然后我非常不推荐不分析 LS

My personal opinion: parsing ls is only dangerous when the filenames contain funny characters like newlines or spaces. If you can guarantee that the filenames do not contain funny characters then parsing ls is quite safe. Still, if you are developing a script which is meant to be run by many people on many systems in many different situations then I very much do recommend to not parse ls.