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

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

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

./alfa/beta/gamma/example.txt

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


当前回答

快速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

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

其他回答

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

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

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

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

你可以用下面的管道:

xargs -0 printf "%s\n"

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

查询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

我缩短了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";

此命令适用于Mac OS X:

find "$1" -type f -print0 | xargs -0 gstat——format '%Y:% Y %n' | sort -nr | cut -d: -f2- | head

在Linux上,正如最初的海报所要求的那样,使用stat而不是gstat。

当然,这个答案是user37078的出色解决方案,从评论晋升为完整答案。我混合了CharlesB在Mac OS x上使用gstat的见解,顺便说一下,我是从MacPorts而不是Homebrew获得的coreutils。

下面是我如何将其打包成一个简单的命令~/bin/ls-recent.sh以供重用:

#!/bin/bash
# ls-recent: list files in a directory tree, most recently modified first
#
# Usage: ls-recent path [-10 | more]
#
# Where "path" is a path to target directory, "-10" is any argument to pass
# to "head" to limit the number of entries, and "more" is a special argument
# in place of "-10" which calls the pager "more" instead of "head".
if [ "more" = "$2" ]; then
   H=more; N=''
else
   H=head; N=$2
fi

find "$1" -type f -print0 |xargs -0 gstat --format '%Y :%y %n' \
    |sort -nr |cut -d: -f2- |$H $N

快速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

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