Get most recent file in a directory on Linux

2019-01-05 09:05发布

Looking for a command that will return the single most recent file in a directory.

Not seeing a limit parameter to ls...

18条回答
地球回转人心会变
2楼-- · 2019-01-05 09:41

The find / sort solution works great until the number of files gets really large (like an entire file system). Use awk instead to just keep track of the most recent file:

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]* //'
查看更多
Evening l夕情丶
3楼-- · 2019-01-05 09:42

I use:

ls -ABrt1 --group-directories-first | tail -n1

It gives me just the file name, excluding folders.

查看更多
干净又极端
4楼-- · 2019-01-05 09:42

All those ls/tail solutions work perfectly fine for files in a directory - ignoring subdirectories.

In order to include all files in your search (recursively), find can be used. gioele suggested sorting the formatted find output. But be careful with whitespaces (his suggestion doesn't work with whitespaces).

This should work with all file names:

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

This sorts by mtime, see man find:

%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.

So just replace %T with %C to sort by ctime.

查看更多
劳资没心,怎么记你
5楼-- · 2019-01-05 09:43

I like echo *(om[1]) (zsh syntax) as that just gives the file name and doesn't invoke any other command.

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-05 09:43

Presuming you don't care about hidden files that start with a .

ls -rt | tail -n 1

Otherwise

ls -Art | tail -n 1
查看更多
三岁会撩人
7楼-- · 2019-01-05 09:44

ls -lAtr | tail -1

The other solutions do not include files that start with '.'.

This command will also include '.' and '..', which may or may not be what you want:

ls -latr | tail -1

查看更多
登录 后发表回答