操作系统:Linux 文件系统类型:ext3 首选解决方案:Bash(脚本/一行程序)、Ruby或Python

我有几个目录,其中有几个子目录和文件。我需要列出所有这些目录,其构造方式是将每个一级目录列在其中最新创建/修改文件的日期和时间旁边。

为了说明这一点,如果我接触一个文件或修改它的内容向下几级子目录,该时间戳应该显示在第一级目录名旁边。假设我有一个这样的目录:

./alfa/beta/gamma/example.txt

我修改了文件example.txt的内容,我需要在第一级目录alfa旁边以人类可读的形式显示时间,而不是epoch。我已经尝试了一些使用find, xargs, sort和类似的东西,但我不能绕过“alfa”的文件系统时间戳不改变的问题,当我创建/修改文件的几个级别。


当前回答

查询N分钟前文件状态被修改的所有文件。

find -cmin -N

例如:

find -cmin -5

使用-ctime代替-cmin:

find -ctime -3

在FreeBSD和MacOS上:您还可以使用-ctime n[smhdw]表示秒、分钟、小时、天和周。如果没有提供单位,Days是默认值。

例子:

# FreeBSD and MacOS only:
find . -ctime -30s
find . -ctime -15
find . -ctime -52w

其他回答

对于那些面对的人

stat: unrecognized option: format

当执行Heppo的答案(查找$1 -type f -exec stat——format '%Y:% Y %n' "{}" \;| sort -nr | cut -d: -f2- | head)

请尝试使用-c键来替换——format,最后调用将是:

find $1 -type f -exec stat -c '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head

这在一些Docker容器中为我工作,在那里stat不能使用——format选项。

快速Bash功能:

# findLatestModifiedFiles(directory, [max=10, [format="%Td %Tb %TY, %TT"]])
function findLatestModifiedFiles() {
    local d="${1:-.}"
    local m="${2:-10}"
    local f="${3:-%Td %Tb %TY, %TT}"

    find "$d" -type f -printf "%T@ :$f %p\n" | sort -nr | cut -d: -f2- | head -n"$m"
}

在目录中查找最新修改的文件:

findLatestModifiedFiles "/home/jason/" 1

您还可以指定自己的日期/时间格式作为第三个参数。

这篇文章中的Perl和Python解决方案帮助我解决了Mac OS X上的这个问题:

如何递归地列出按修改日期排序的文件(没有可用的stat命令!)

引自帖子:

Perl:

find . -type f -print |
perl -l -ne '
    $_{$_} = -M;  # store file age (mtime - now)
    END {
        $,="\n";
        print sort {$_{$b} <=> $_{$a}} keys %_;  # print by decreasing age
    }'

Python:

find . -type f -print |
python -c 'import os, sys; times = {}
for f in sys.stdin.readlines(): f = f[0:-1]; times[f] = os.stat(f).st_mtime
for f in sorted(times.iterkeys(), key=lambda f:times[f]): print f'

在mac上我用这个

find . -type f -exec stat -f "%m %N" "{}" \; | sort -nr | perl -n -e '@a = split / /;print `ls -l $a[1]`' | vim -

如果你想过滤一些文件,你可以使用grep与regexp,即。

find . -type f -exec stat -f "%m %N" "{}" \; | sort -nr | grep -v -E \.class$ | perl -n -e '@a = split / /;print `ls -l $a[1]`' | vim -

忽略隐藏文件-良好和快速的时间戳

下面介绍如何查找并列出带有子目录的目录中最新修改的文件。隐藏文件被故意忽略。然而文件名中的空格处理得很好-不是说你应该使用它们!时间格式可以自定义。

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

2017.01.25 18h23 Wed ./indenting/Shifting blocks visually.mht
2016.12.11 12h33 Sun ./tabs/Converting tabs to spaces.mht
2016.12.02 01h46 Fri ./advocacy/2016.Vim or Emacs - Which text editor do you prefer?.mht
2016.11.09 17h05 Wed ./Word count - Vim Tips Wiki.mht

更多的发现可以通过以下链接找到。