Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs lisp: How can I get the newest file in a directory?

Given the path of a directory, how can I return the path of the newest file in that directory?

like image 741
arvidj Avatar asked Jun 17 '15 08:06

arvidj


2 Answers

Using built-in APIs can achieve as well:

(defun latest-file (path)
  "Get latest file (including directory) in PATH."
  (car (directory-files path 'full nil #'file-newer-than-file-p)))

(latest-file "~/.emacs.d") ;; => "/Users/xcy/.emacs.d/var"

If you also needs files under sub-directory, use directory-files-recursively rather than directory-files. If you want to exclude directories, filter the file/directory list first by using file-directory-p.

like image 143
xuchunyang Avatar answered Sep 22 '22 17:09

xuchunyang


Using f:

(defun aj-fetch-latest (path)
  (let ((e (f-entries path)))
    (car (sort e (lambda (a b)
                   (not (time-less-p (aj-mtime a)
                                     (aj-mtime b))))))))
(defun aj-mtime (f) (let ((attrs (file-attributes f))) (nth 5 attrs)))
like image 40
arvidj Avatar answered Sep 22 '22 17:09

arvidj