Get most recent file in a directory on Linux

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

    If you want to get the most recent changed file also including any subdirectories you can do it with this little oneliner:

    find . -type f -exec stat -c '%Y %n' {} \; | sort -nr | awk -v var="1" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t "+%b %d %T %Y"); echo "$d -- $f"; done
    

    If you want to do the same not for changed files, but for accessed files you simple have to change the

    %Y parameter from the stat command to %X. And your command for most recent accessed files looks like this:

    find . -type f -exec stat -c '%X %n' {} \; | sort -nr | awk -v var="1" 'NR==1,NR==var {print $0}' | while read t f; do d=$(date -d @$t "+%b %d %T %Y"); echo "$d -- $f"; done
    

    For both commands you also can change the var="1" parameter if you want to list more than just one file.

提交回复
热议问题