Search code examples
emacselisp

how to delete the repeat lines in emacs


I have a text with a lots of lines, my question is how to delete the repeat lines in emacs? using the command in emacs or elisp packages without external utils.

for example:

this is line a
this is line b
this is line a

to remove the 3rd line (same as 1st line)

this is line a
this is line b

Solution

  • Put this code to your .emacs:

    (defun uniq-lines (beg end)
      "Unique lines in region.
    Called from a program, there are two arguments:
    BEG and END (region to sort)."
      (interactive "r")
      (save-excursion
        (save-restriction
          (narrow-to-region beg end)
          (goto-char (point-min))
          (while (not (eobp))
            (kill-line 1)
            (yank)
            (let ((next-line (point)))
              (while
                  (re-search-forward
                   (format "^%s" (regexp-quote (car kill-ring))) nil t)
                (replace-match "" nil nil))
              (goto-char next-line))))))
    

    Usage:

    M-x uniq-lines