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

ls -altR . | head -n 3

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


当前回答

我发现上面的命令很有用,但对于我的情况,我需要查看文件的日期和时间,我有一个问题,几个文件的名称中有空格。 这是我的工作解决方案。

find . -type f -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d" " | sed 's/.*/"&"/' | xargs ls -l

其他回答

我费了好大劲才找到Solaris 10下最后一个修改过的文件。find没有printf选项,stat不可用。我发现下面这个方法对我来说很管用:

find . -type f | sed 's/.*/"&"/' | xargs ls -E | awk '{ print $6," ",$7 }' | sort | tail -1

要显示文件名,请使用

find . -type f | sed 's/.*/"&"/' | xargs ls -E | awk '{ print $6," ",$7," ",$9 }' | sort | tail -1

解释

找到。-type f查找并列出所有文件 sed的s /。*/"&"/'将路径名用引号括起来以处理空白 xargs ls -E将带引号的路径发送到ls, -E选项确保返回完整的时间戳(格式为年-月-日小时-分-秒-纳秒) Awk '{print $6," ",$7}'只提取日期和时间 Awk '{print $6," ",$7," ",$9}'提取日期,时间和文件名 Sort返回按日期排序的文件 Tail -1只返回最后修改的文件

使用find -具有良好和快速的时间戳

下面介绍如何查找并列出带有子目录的目录中最新修改的文件。隐藏文件被故意忽略。时间格式可以自定义。

$ find . -type f -not -path '*/\.*' -printf '%TY-%Tm-%Td %TH:%TM %Ta %p\n' |sort -nr |head -n 10

结果

处理文件名中的空格非常好-不是说这些应该被使用!

2017-01-25 18:23 Wed ./indenting/Shifting blocks visually.mht
2016-12-11 12:33 Sun ./tabs/Converting tabs to spaces.mht
2016-12-02 01:46 Fri ./advocacy/2016.Vim or Emacs - Which text editor do you prefer?.mht
2016-11-09 17:05 Wed ./Word count - Vim Tips Wiki.mht

More

更多的发现大量以下的链接。

我一直在使用类似的东西,以及最近修改的文件的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倍。

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

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

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

我发现以下内容更简短,输出可解释性更强:

find . -type f -printf '%TF %TT %p\n' | sort | tail -1

给定标准化ISO格式datetimes的固定长度,字典排序就可以了,我们不需要在排序上使用-n选项。

如果你想再次删除时间戳,你可以使用:

find . -type f -printf '%TFT%TT %p\n' | sort | tail -1 | cut -f2- -d' '