7

sort-fields and sort-numeric-fields work great; but the field separator is whitespace. I would like to use a different delimiter (e.g.: [colon-char]).

I want this feature because I find myself resorting the passwd files records by UID via vipw.

I suppose I could start a shell and run something like sort -n -t ':' -k3 /etc/passwd and replace; but that seems clumsy and sort-numeric-fields is tantalizingly close to perfect.

2 Answers 2

4

See the code for sort-fields? Have you tried substituting a regexp that matches your preferred separators for the hard-coded regexp in sort-fields, which matches whitespace? Untested whether just changing that regexp does the trick - but that would be the place to start, I think.

This the sort-fields code:

(defun sort-fields (field beg end)
  "..."
  (interactive "p\nr")
  (let ;; To make `end-of-line' and etc. to ignore fields.
      ((inhibit-field-text-motion t))
    (sort-fields-1 field beg end
           (function (lambda () (sort-skip-fields field) nil))
       (function (lambda () (skip-chars-forward "^ \t\n"))))))
                                             ;; ^^^^^^^^
                                             ;; CHANGE TO
                                             ;; MATCH YOUR SEPARATORS

BTW, if such a change is sufficient then you might even consider requesting that Emacs Dev add an optional regexp arg that matches the separators. To do that, use M-x report-emacs-bug.

1
  • I'm so dramatically lisp-inept, I did not consider writing a new defun; but you're correct; that's the elegant way. I will see what I can come up with.
    – ericx
    Sep 3, 2015 at 19:25
2

Just use sort-regexp-fields. (Don't change sort.el or redefine any of its functions.)

2
  • 1
    Please elaborate - explain how "Just use sort-regexp-fields" answers the question. Maybe say something about how to use it or what it does.
    – Drew
    Aug 7, 2019 at 22:45
  • I agree with Drew, particularly since sort-regexp-fields wants a regexp that identifies the records to sort, not the field separator, so while you can use it to "change the field separator", for that case it might not be very comfortable.
    – Omar
    Aug 11, 2019 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.