Get most recent file in a directory on Linux

前端 未结 21 2377
余生分开走
余生分开走 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:00

    A note about reliability:

    Since the newline character is as valid as any in a file name, any solution that relies on lines like the head/tail based ones are flawed.

    With GNU ls, another option is to use the --quoting-style=shell-always option and a bash array:

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

    (add the -A option to ls if you also want to consider hidden files).

    If you want to limit to regular files (disregard directories, fifos, devices, symlinks, sockets...), you'd need to resort to GNU find.

    With bash 4.4 or newer (for readarray -d) and GNU coreutils 8.25 or newer (for 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]}"
    

    Or recursively:

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

    Best here would be to use zsh and its glob qualifiers instead of bash to avoid all this hassle:

    Newest regular file in the current directory:

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

    Including hidden ones:

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

    Second newest:

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

    Check file age after symlink resolution:

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

    Recursively:

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

    Also, with the completion system (compinit and co) enabled, Ctrl+Xm becomes a completer that expands to the newest file.

    So:

    vi Ctrl+Xm

    Would make you edit the newest file (you also get a chance to see which it before you press Return).

    vi Alt+2Ctrl+Xm

    For the second-newest file.

    vi *.cCtrl+Xm

    for the newest c file.

    vi *(.)Ctrl+Xm

    for the newest regular file (not directory, nor fifo/device...), and so on.

提交回复
热议问题