在进行递归调用时,ls似乎没有正确地对文件进行排序:

ls -altR . | head -n 3

如何在目录(包括子目录)中找到最近修改的文件?


当前回答

这似乎工作得很好,即使是子目录:

find . -type f | xargs ls -ltr | tail -n 1

如果文件太多,细化查找。

其他回答

接着@plundra的回答,下面是BSD和OS X版本:

find . -type f -print0 \
| xargs -0 stat -f "%m %N" \
| sort -rn | head -1 | cut -f2- -d" "

这给出了一个排序的列表:

find . -type f -ls 2>/dev/null | sort -M -k8,10 | head -n5

通过在sort命令中添加'-r'来颠倒顺序。如果你只想要文件名,在'| head'之前插入"awk '{print $11}' |"

这将递归地将当前目录中所有目录的修改时间更改为每个目录中的最新文件:

for dir in */; do find $dir -type f -printf '%T@ "%p"\n' | sort -n | tail -1 | cut -f2- -d" " | xargs -I {} touch -r {} $dir; done

我一直在使用类似的东西,以及最近修改的文件的top-k列表。对于大型目录树,避免排序会快得多。如果是最近修改最多的文件:

find . -type f -printf '%T@ %p\n' | perl -ne '@a=split(/\s+/, $_, 2); ($t,$f)=@a if $a[0]>$t; print $f if eof()'

在一个包含170万个文件的目录中,我在3.4秒内获得了最新的一个文件,与使用排序的25.5秒解决方案相比,速度提高了7.5倍。

下面的命令在Solaris上运行:

find . -name "*zip" -type f | xargs ls -ltr | tail -1