Get most recent file in a directory on Linux

前端 未结 21 2200
余生分开走
余生分开走 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 09:42

    I personally prefer to use as few not built-in bash commands as I can (to reduce the number of expensive fork and exec syscalls). To sort by date the ls needed to be called. But using of head is not really necessary. I use the following one-liner (works only on systems supporting name pipes):

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

    or to get the name of the oldest file

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

    (Mind the space between the two '<' marks!)

    If the hidden files are also needed -A arg could be added.

    I hope this could help.

    0 讨论(0)
  • 2020-11-27 09:43

    Finding the most current file in every directory according to a pattern, e.g. the sub directories of the working directory that have name ending with "tmp" (case insensitive):

    find . -iname \*tmp -type d -exec sh -c "ls -lArt {} | tail -n 1" \;
    
    0 讨论(0)
  • 2020-11-27 09:44
    ls -Art | tail -n 1
    

    Not very elegant, but it works.

    0 讨论(0)
  • 2020-11-27 09:44

    I use:

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

    It gives me just the file name, excluding folders.

    0 讨论(0)
  • 2020-11-27 09:45

    try this simple command

    ls -ltq  <path>  | head -n 1
    

    If you want file name - last modified, path = /ab/cd/*.log

    If you want directory name - last modified, path = /ab/cd/*/

    0 讨论(0)
  • 2020-11-27 09:45
    ls -Frt | grep "[^/]$" | tail -n 1
    
    0 讨论(0)
提交回复
热议问题