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

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

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

./alfa/beta/gamma/example.txt

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


当前回答

下面返回一个字符串,包含时间戳和带有最近时间戳的文件名:

find $Directory -type f -printf "%TY-%Tm-%Td-%TH-%TM-%TS %p\n" | sed -r 's/([[:digit:]]{2})\.([[:digit:]]{2,})/\1-\2/' |     sort --field-separator='-' -nrk1 -nrk2 -nrk3 -nrk4 -nrk5 -nrk6 -nrk7 | head -n 1

导致表单的输出: < yy-mm-dd-hh-mm-ss。nanosec > <文件名>

其他回答

我显示的是最新的访问时间,你可以很容易地修改它来做最新的修改时间。

有两种方法:


If you want to avoid global sorting which can be expensive if you have tens of millions of files, then you can do (position yourself in the root of the directory where you want your search to start): Linux> touch -d @0 /tmp/a; Linux> find . -type f -exec tcsh -f -c test `stat --printf="%X" {}` -gt `stat --printf="%X" /tmp/a` ; -exec tcsh -f -c touch -a -r {} /tmp/a ; -print The above method prints filenames with progressively newer access time and the last file it prints is the file with the latest access time. You can obviously get the latest access time using a "tail -1". You can have find recursively print the name and access time of all files in your subdirectory and then sort based on access time and the tail the biggest entry: Linux> \find . -type f -exec stat --printf="%X %n\n" {} \; | \sort -n | tail -1

现在你知道了……

下面是一个版本,它可以处理包含空格、换行符和glob字符的文件名:

find . -type f -printf "%T@ %p\0" | sort -zk1nr

找到……-printf打印文件修改时间(Epoch值),后面跟着空格和以\0结尾的文件名。 sort -zk1nr读取以NUL终止的数据,并对其反向排序

由于问题被标记为Linux,我假设GNU核心实用程序是可用的。

你可以用下面的管道:

xargs -0 printf "%s\n"

打印以换行符结束的按修改时间(最近的第一个)排序的修改时间和文件名。

这是我正在使用的(非常有效):

function find_last () { find "${1:-.}" -type f -printf '%TY-%Tm-%Td %TH:%TM %P\n' 2>/dev/null | sort | tail -n "${2:-10}"; }

优点:

不管扫描多少文件,它只生成3个进程 处理包含空格的文件名 适用于大量文件

用法:

find_last [dir [number]]

地点:

目录-要搜索的目录[当前目录] Number -显示[10]的最新文件数

find_last /etc 4的输出如下所示:

2019-07-09 12:12 cups/printers.conf
2019-07-09 14:20 salt/minion.d/_schedule.conf
2019-07-09 14:31 network/interfaces
2019-07-09 14:41 environment

这也可以用Bash中的递归函数来完成。

设F是一个函数,它显示文件的时间,该文件必须按字典顺序排序yyyy-mm-dd,等等,(依赖于操作系统?)

F(){ stat --format %y "$1";}                # Linux
F(){ ls -E "$1"|awk '{print$6" "$7}';}      # SunOS: maybe this could be done easier

R,遍历目录的递归函数:

R(){ local f;for f in "$1"/*;do [ -d "$f" ]&&R $f||F "$f";done;}

最后

for f in *;do [ -d "$f" ]&&echo `R "$f"|sort|tail -1`" $f";done

我的.profile中有一个我经常使用的别名:

$ alias | grep xlogs
xlogs='sudo find . \( -name "*.log" -o -name "*.trc" \) -mtime -1 | sudo xargs ls -ltr --color | less -R'

所以它做了你正在寻找的(除了它不遍历更改日期/时间多层)-寻找最新的文件(*.log和*.log)。本例为储税券文件);此外,它只发现在最后一天修改的文件,然后按时间排序,并通过较少的管道输出:

sudo find . \( -name "*.log" -o -name "*.trc" \) -mtime -1 | sudo xargs ls -ltr --color | less -R

注意,我在某些服务器上没有root,但总是有sudo,所以你可能不需要那部分。