MamboLevis
MamboLevis

Reputation: 13

Sort directory-files

I have the following directories:

When I use

(list (directory-files dir t "\\(mod\\)\\([0-9]\\)" nil))

the output is:

As you can see, mod100 is not in the correct position.The desired output is:

Thank you for your advice

Upvotes: 1

Views: 76

Answers (2)

Jürgen Hötzel
Jürgen Hötzel

Reputation: 19717

Supply a custom predicate function extracting the numeric part:

(sort
 (directory-files dir t "\\(mod\\)\\([0-9]\\)" nil)
 (lambda (x y)
   (<
    (string-to-number (replace-regexp-in-string ".*mod\\([[:digit:]]+\\).*" "\\1" x))
    (string-to-number (replace-regexp-in-string ".*mod\\([[:digit:]]+\\).*" "\\1" y)))))

Upvotes: 1

Rorschach
Rorschach

Reputation: 32416

As described in the help doc for directory-files sorting uses the predicate string-lessp, for which (string-lessp "100" "9") returns t. You could write your own predicate and set nosort to true and use cl-sort to sort the contents by extracting the numeric part of the strings. If you are on a machine with access to sort -V, you could just wrap a shell command,

(defun my-sort (&optional dir)
  (interactive "D")
  (with-temp-buffer
    (shell-command
     (concat "ls " (shell-quote-argument (or dir default-directory)) "| sort -V")
     (current-buffer))
    (split-string (buffer-string) "\n")))

Using sort's version sorting should result in the desired ordering.

Upvotes: 0

Related Questions