Bash函数查找最新的文件匹配模式
在 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
脚本中有这个.
I want the newest file that starts with 'b2'. How do I do this in bash? I need to have this in my ~/.bash_profile
script.
ls
命令有一个参数 -t
可以按时间排序.然后,您可以使用 head -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
但要注意:为什么不应该解析 ls 的输出
我的个人观点:解析 ls
仅在文件名可以包含有趣的字符(如空格或换行符)时才是危险的.如果你能保证文件名不包含有趣的字符,那么解析 ls
是非常安全的.
My personal opinion: parsing ls
is only dangerous when the filenames can contain funny characters like spaces or newlines. If you can guarantee that the filenames will not contain funny characters then parsing ls
is quite safe.
如果您正在开发一个脚本,该脚本旨在由许多人在许多不同情况下在许多系统上运行,那么我非常建议不要解析 ls
.
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
.
以下是正确"的方法:如何找到最新的(最新的、最早的、最旧的) 目录中的文件?
unset -v latest
for file in "$dir"/*; do
[[ $file -nt $latest ]] && latest=$file
done