How can I randomly sort lines in a buffer?

I have a buffer of words and phrases in sorted order, and I would like the strings to be sorted in random order. How can I do this using the emacs built-in function or using elisp?

For example, given

bar
elisp
emacs
foo
hello world
the quick brown fox

I need some completely random result like:

foo
the quick brown fox
hello world
elisp
emacs
bar

or...

hello world
elisp
bar
the quick brown fox
foo
emacs

+7
source share
4 answers

randomize-region.el seems to do what you want.

+6
source

Using Bash on GNU / Linux:

Similar to Sean's decision, select an area and then:

C-u M-| shuf

Explanation:

M- | Bash shuf. shuf shuffles . C-u shuf .

+9

, sort-lines .

reverse (, ) , sort-subr.

(defun my-random-sort-lines (beg end)
  "Sort lines in region randomly."
  (interactive "r")
  (save-excursion
    (save-restriction
      (narrow-to-region beg end)
      (goto-char (point-min))
      (let ;; To make `end-of-line' and etc. to ignore fields.
          ((inhibit-field-text-motion t))
        (sort-subr nil 'forward-line 'end-of-line nil nil
                   (lambda (s1 s2) (eq (random 2) 0)))))))

:
M-x find-function RET sort-lines RET

+7

Perl, , , C-u M-| perl -MList::Util=shuffle -e 'print shuffle <STDIN>'.

, .

+4

All Articles