Get most recent file in a directory on Linux

前端 未结 21 2203
余生分开走
余生分开走 2020-11-27 09:24

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

Not seeing a limit parameter to ls...

相关标签:
21条回答
  • 2020-11-27 10:05

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

    0 讨论(0)
  • 2020-11-27 10:05

    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]* //'
    
    0 讨论(0)
  • 2020-11-27 10:07

    Shorted variant based on dmckee's answer:

    ls -t | head -1
    
    0 讨论(0)
提交回复
热议问题