如何find某个名字的最新文件?

假设我有一个在子目录中有许多同名文件的目录(例如,在为多篇学术论文保留BibTeX文件时出现)。

用特定名称查找文件的最新版本的最佳方法是什么?

我已经拿出了下面的命令

find . -name "someFile" -exec ls -alF {} \; 

其中列出了所有名为someFile的文件以及它们的date,但是不会将它们从旧到新sorting

请注意, ls-t选项不能在这里使用,因为它是针对每个文件单独运行的。

你可以使用statfind

 find . -name "someFile" -exec stat -c '%n:%Y' {} + | sort -t : -k2 | cut -d : -f1 
  • stat命令是从文件修改时间的EPOCH值开始按时间打印每个文件名
  • sort是使用第二个键(修改时间)排序stat的输出
  • cut只是选择第一列(文件名)

编辑:根据下面的评论,你可以使用:

 while IFS=: read -rft; do echo "$f <$(date -d @$t)>" done < <(find . -name "someFile" -exec stat -c '%N:%Y' '{}' + | sort -t : -k2) 

编辑2:在Linux系统上,你可以做:

 find . -name "someFile" -printf "%p:%T@\n" | sort -t : -k2 

更新

根据OP。 将所提出的解决方案结合起来,结果如下,非常干净:

 find . -name "someFile" -exec ls -latR {} + 

它显示文件的所有版本,最新的第一个。 这将需要GNU发现作为BSD发现没有-ls选项。

另一个解决方案(除了anubhava)将使用正向引号来执行ls find的结果,这将允许您使用-t修饰符:

 ls -alFt `find . -name "somefile"` 

然后,如果您倾向于这样做,您可以使用一系列cut ,转换和head文件来提取文件名称:

 ls -alFt `find . -name "bla.txt"` | rev | cut -d" " -f1 | rev | head -1 

最近的文件(前20):

 find . -name someFile\* -type f -exec stat -c "%W %n" -- {} \; | sort -nr | head -n20 

最老的文件(前20名)

 find . -name someFile\* -type f -exec stat -c "%W %n" -- {} \; | sort -n | head -n20 

注意:您需要安装coreutils才能使用stat命令。

您可以根据您的需要使用不同的时间标志:

 %w time of file birth, human-readable; - if unknown %W time of file birth, seconds since Epoch; 0 if unknown %x time of last access, human-readable %X time of last access, seconds since Epoch %y time of last modification, human-readable %Y time of last modification, seconds since Epoch %z time of last change, human-readable %Z time of last change, seconds since Epoch 

请参阅: stat --help以获取更多选项。

在BSD / OSX上,你必须检查不同的参数,或从coreutils软件包安装GNU stat

我一直喜欢“后来”的助记符

ls -latr | grep文件名

文件名的最近时间戳将在最下面

将所提出的解决方案结合起来,结果如下,非常干净:

 find . -name "someFile" -exec ls -latR {} + 

它显示文件的所有版本,最新的第一个。