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

没有看到ls的limit参数…


当前回答

所有这些ls/tail解决方案都非常适用于目录中的文件—忽略子目录。

为了在搜索中包含所有文件(递归地),可以使用find。Gioele建议对格式化的查找输出进行排序。但是要小心使用空格(他的建议不适用于空格)。

这应该适用于所有文件名:

find $DIR -type f -printf "%T@ %p\n" | sort -n | sed -r 's/^[0-9.]+\s+//' | tail -n 1 | xargs -I{} ls -l "{}"

这一分类由时,见人发现:

%Ak    File's  last  access  time in the format specified by k, which is either `@' or a directive for the C `strftime' function.  The possible values for k are listed below; some of them might not be available on all systems, due to differences in `strftime' between systems.
       @      seconds since Jan. 1, 1970, 00:00 GMT, with fractional part.
%Ck    File's last status change time in the format specified by k, which is the same as for %A.
%Tk    File's last modification time in the format specified by k, which is the same as for %A.

用%C替换%T,按ctime排序。

其他回答

关于可靠性注意事项:

由于换行符和文件名中的任何字符一样有效,任何依赖于行(如基于头/尾的行)的解决方案都是有缺陷的。

在GNU ls中,另一个选项是使用——quote -style=shell-always选项和一个bash数组:

eval "files=($(ls -t --quoting-style=shell-always))"
((${#files[@]} > 0)) && printf '%s\n' "${files[0]}"

(如果您还想考虑隐藏文件,则在ls中添加-A选项)。

如果您希望限制到常规文件(忽略目录、fifo、设备、符号链接、套接字……),则需要求助于GNU find。

使用bash 4.4或更新版本(用于readarray -d)和GNU coreutils 8.25或更新版本(用于cut -z):

readarray -t -d '' files < <(
  LC_ALL=C find . -maxdepth 1 -type f ! -name '.*' -printf '%T@/%f\0' |
  sort -rzn | cut -zd/ -f2)

((${#files[@]} > 0)) && printf '%s\n' "${files[0]}"

或递归地:

readarray -t -d '' files < <(
  LC_ALL=C find . -name . -o -name '.*' -prune -o -type f -printf '%T@%p\0' |
  sort -rzn | cut -zd/ -f2-)

这里最好使用zsh和它的glob限定符,而不是bash来避免所有这些麻烦:

当前目录下最新的常规文件:

printf '%s\n' *(.om[1])

包括隐藏的:

printf '%s\n' *(D.om[1])

第二个最新的:

printf '%s\n' *(.om[2])

符号链接解析后检查文件年龄:

printf '%s\n' *(-.om[1])

递归地:

printf '%s\n' **/*(.om[1])

此外,启用了补全系统(compinit和co)后,Ctrl+Xm就变成了扩展到最新文件的补全器。

So:

vi Ctrl+Xm

会让你编辑最新的文件(你也有机会看到它在你按下返回)。

vi Alt+2Ctrl+Xm

对于第二个最新的文件。

vi *.cCtrl+Xm

对于最新的c文件。

vi *(.)Ctrl+Xm

对于最新的常规文件(不是目录,也不是fifo/device…),等等。

ls -lAtr | tail -1

其他解决方案不包括以“。”开头的文件。

该命令还包括'。'和'..,这可能是也可能不是你想要的:

Ls -latr | tail -1

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

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

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

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

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

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

我希望这能有所帮助。

使用R递归选项..你可以认为这是对好的答案的增强

ls -arRtlh | tail -50

递归地:

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