arrays - 文件位置的bash数组 - 如何找到最后更新的文件?
问题描述
有一个从我需要循环并找出最新的并打印最新的定位命令构建的文件数组。我们有一个名为 randomname-properties.txt 的属性文件,它位于多个位置,有时称为 randomname-properties.txt.bak 或 randomname-properties.txt.old。示例如下
目录结构
/opt/test/something/randomname-properties.txt
/opt/test2/something/randomname-properties.txt.old
/opt/test3/something/randomname-properties.txt.bak
/opt/test/something1/randomname-properties.txt.working
代码
#Builds list of all files
PropLoc=(`locate randomname-properties.txt`)
#Parse list and remove older file
for i in ${PropLoc[@]} ; do
if [ ${PropLoc[0]} -ot ${PropLoc[1]} ] ; then
echo "Removing ${PropLoc[0]} from the list as it is older"
#Below should rebuild the array while removing the older element
PropLoc=( "${PropLoc[@]/$PropLoc[0]}" )
fi
done
echo "Latest file found is ${PropLoc[@]}"
总的来说,这是行不通的。目前看来,它甚至没有进入循环,因为前两个文件具有与去年相同的时间戳(对于超过一年的事情,似乎在过去的一天没有冲突)。关于如何让它正常工作的任何想法?谢谢
解决方案
您可以使用ls -t
,它将按修改时间对文件进行排序。第一行将是最新的文件。
newest=$(ls -t "${PropLoc[@]}" | head -n 1)
只要没有文件名包含换行符,这应该可以工作。
不要忘记引用您的变量,以防它们包含空格或通配符。
推荐阅读
- javascript - 我无法将发布请求从反应表单发送到烧瓶服务器
- youtrack - YouTrack 中的隐藏/暂停问题
- c - C/ 从文件到数组的字符串数据。分段故障
- sql - sql server error = 当子查询跟随 =, !=, <, <= , >, >= 或当子查询用作表达式时,这是不允许的
- c++ - 如何使用openssl通过ocsp验证证书
- laravel-5 - 我想在数据库表中添加图像的名称,而不是图像的整个路径,我想使用 Factory 和 Seeds
- html - 使用 [(ngModel)] 并有一个空的选择元素
- python - 如何使用 python 在 Gurobi 中激活(或停用)切割?我在哪里可以找到这些削减的文档?
- angular - 事件发射器:模板对发射的事件没有反应
- airflow - 气流 DAG 循环 - 如何使每个迭代顺序而不是并行