使`delete-duplicate-lines`忽略空行和某些单词


9

我正在以组织方式编辑文本,重复了几行,因为它们位于同一主题的不同文件的一部分。

我想使用delete-duplicate-lines删除重复的行,但是,该命令也删除了空白行,这是我不想要的(否则我将没有段落!)。我想忽略某些行中单独存在的单词,例如“ Resume”,它在文本中重复了很多次,但是由于需要,所以我想保留它。

Answers:


5

忽略空白行

您可以delete-duplicate-lines通过调用来告诉忽略空行

C-u C-u C-u M-x delete-duplicate-lines RET

如果您不想C-u在调用时被击中多次delete-duplicate-lines,则可以将其包装在自定义命令中,然后将该命令绑定到您选择的键序列上:

(defun delete-duplicate-lines-keep-blanks ()
  (interactive)
  (delete-duplicate-lines (region-beginning) (region-end) nil nil t))

(global-set-key (kbd "C-c d") 'delete-duplicate-lines-keep-blanks)

忽略与正则表达式匹配的行

至于问题的第二部分,我认为您无法使用的内置版本来实现所需的功能delete-duplicate-lines。但是,您可以使用命令的修改版本(默认情况下也保留空白行):

(defun delete-duplicate-lines
    (beg end keep &optional reverse adjacent keep-blanks interactive)
  (interactive
   (progn
     (barf-if-buffer-read-only)
     (list (region-beginning) (region-end)
           (read-string "Keep lines matching regexp: ") ; Prompt for regexp to keep
           (equal current-prefix-arg '(4))
           (equal current-prefix-arg '(16))
           t                                            ; Keep blanks by default
           t)))
  (let ((lines (unless adjacent (make-hash-table :test 'equal)))
        line prev-line
        (count 0)
        (beg (copy-marker beg))
        (end (copy-marker end)))
    (save-excursion
      (goto-char (if reverse end beg))
      (if (and reverse (bolp)) (forward-char -1))
      (while (if reverse
             (and (> (point) beg) (not (bobp)))
               (and (< (point) end) (not (eobp))))
        (setq line (buffer-substring-no-properties
                (line-beginning-position) (line-end-position)))
        (if (or (and keep-blanks (string= "" line))
                (string-match keep line))               ; Ignore line if it
                                                        ; matches regexp to keep
            (forward-line 1)
          (if (if adjacent (equal line prev-line) (gethash line lines))
              (progn
                (delete-region (progn (forward-line 0) (point))
                               (progn (forward-line 1) (point)))
                (if reverse (forward-line -1))
                (setq count (1+ count)))
            (if adjacent (setq prev-line line) (puthash line t lines))
            (forward-line (if reverse -1 1))))))
    (set-marker beg nil)
    (set-marker end nil)
    (when interactive
      (message "Deleted %d %sduplicate line%s%s"
               count
               (if adjacent "adjacent " "")
               (if (= count 1) "" "s")
               (if reverse " backward" "")))
    count))

此版本的delete-duplicate-lines会提示您输入正则表达式,并保留所有与该正则表达式匹配的行。例如,要使所有行都包含单词,Resume您可以执行以下操作:

M-x delete-duplicate-lines RET ^Resume$ RET

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.