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

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

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

./alfa/beta/gamma/example.txt

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


当前回答

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

有两种方法:


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

现在你知道了……

其他回答

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

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 > <文件名>

试试这个:

#!/bin/bash
stat --format %y $(ls -t $(find alfa/ -type f) | head -n 1)

它使用find来收集目录中的所有文件,ls按修改日期排序,head用于选择第一个文件,最后使用stat以良好的格式显示时间。

此时,对于名称中有空格或其他特殊字符的文件是不安全的。如果它还不能满足你的需求,就写一篇推荐信。

这实际上应该做OP指定的事情:

Bash中的一行代码:

$ for first_level in `find . -maxdepth 1 -type d`; do find $first_level -printf "%TY-%Tm-%Td %TH:%TM:%TS $first_level\n" | sort -n | tail -n1 ; done

给出如下输出:

2020-09-12 10:50:43.9881728000 .
2020-08-23 14:47:55.3828912000 ./.cache
2018-10-18 10:48:57.5483235000 ./.config
2019-09-20 16:46:38.0803415000 ./.emacs.d
2020-08-23 14:48:19.6171696000 ./.local
2020-08-23 14:24:17.9773605000 ./.nano

中所请求的,即使是在子文件夹中,也会列出这些文件夹中最新文件的人类可读时间戳的每个一级目录

“我需要列出所有这些被构建的目录 使每个一级目录都列在日期旁边的一种方法 以及其中最新创建/修改文件的时间。”

对于那些面对的人

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选项。

我缩短了Daniel Böhmer对这句话的精彩回答:

stat --printf="%y %n\n" $(ls -tr $(find * -type f))

如果文件名中有空格,您可以使用以下修改:

OFS="$IFS";IFS=$'\n';stat --printf="%y %n\n" $(ls -tr $(find . -type f));IFS="$OFS";