寻找返回目录中最新文件的命令。

没有看到ls的limit参数…


当前回答

只有Bash内置程序,紧跟BashFAQ/003:

shopt -s nullglob

for f in * .*; do
    [[ -d $f ]] && continue
    [[ $f -nt $latest ]] && latest=$f
done

printf '%s\n' "$latest"

其他回答

这是一个递归版本(即,它在某个目录或其任何子目录中查找最近更新的文件)

find /dir/path -type f -printf "%T@ %p\n" | sort -n | cut -d' ' -f 2- | tail -n 1

命令行简单的外行解释:

find /dir/path -type f finds all the files in the directory -printf "%T@ %p\n" prints a line for each file where %T@ is the float seconds since 1970 epoch and %p is the filename path and \n is the new line character for more info see man find | is a shell pipe (see man bash section on Pipelines) sort -n means to sort on the first column and to treat the token as numerical instead of lexicographic (see man sort) cut -d' ' -f 2- means to split each line using the character and then to print all tokens starting at the second token (see man cut) NOTE: -f 2 would print only the second token tail -n 1 means to print the last line (see man tail)

查找/排序解决方案工作得很好,直到文件数量变得非常大(比如整个文件系统)。使用awk来跟踪最近的文件:

find $DIR -type f -printf "%T@ %p\n" | 
awk '
BEGIN { recent = 0; file = "" }
{
if ($1 > recent)
   {
   recent = $1;
   file = $0;
   }
}
END { print file; }' |
sed 's/^[0-9]*\.[0-9]* //'

我喜欢echo *(om[1]) (zsh语法),因为它只给出文件名,而不调用任何其他命令。

如果你想获得最近修改的文件,也包括任何子目录,你可以用这个小的联机程序:

find . -type f -exec stat -c '%Y %n' {} \; | sort -nr | awk -v var="1" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t "+%b %d %T %Y"); echo "$d -- $f"; done

如果你想对已更改的文件做同样的事情,但对于已访问的文件,你只需更改

参数%Y从stat命令到%X。对于最近访问的文件,你的命令是这样的:

find . -type f -exec stat -c '%X %n' {} \; | sort -nr | awk -v var="1" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t "+%b %d %T %Y"); echo "$d -- $f"; done

对于这两个命令,如果您想列出多个文件,还可以更改var="1"参数。

我个人更喜欢使用尽可能少的非内置bash命令(以减少昂贵的fork和exec系统调用的数量)。要按日期排序,需要调用ls。但使用头部是没有必要的。我使用以下一行代码(只适用于支持名称管道的系统):

read newest < <(ls -t *.log)

或者获取最古老的文件的名称

read oldest < <(ls -rt *.log)

(注意两个“<”符号之间的空格!)

如果还需要隐藏文件,可以添加一个参数。

我希望这能有所帮助。