jeudi 29 octobre 2015

Delete lines matching a regex; Keep lines matching a regexp

kill-lines-rx will prompt you for a regex and delete all lines matching it. Use with a prefix argument (C-u) to highlight and ask before removing.
(defun kill-lines-rx (&optional ask)
  (interactive "P")
  (save-excursion
    (goto-char (point-min))
    (let ((rx (read-regexp "Rx: ")))
      (while (search-forward-regexp rx nil t)
 (beginning-of-line)
 (set-mark (save-excursion (end-of-line) (point)))
 (when (or (not ask) (y-or-n-p "Kill? "))
   (delete-region (point) (mark))
   (delete-char 1))))))
kill-lines-unless-rx will prompt you for a regex and delete all lines not matching it. Use with a prefix argument (C-u) to highlight and ask before keeping.
(defun kill-lines-unless-rx (&optional ask)
  (interactive "P")
  (let (keep)
    (save-excursion
      (goto-char (point-min))
      (let ((rx (read-regexp "Rx: ")))
 (while (search-forward-regexp rx nil t)
   (beginning-of-line)
   (set-mark (save-excursion (end-of-line) (point)))
   (when (or (not ask) (y-or-n-p "Keep? "))
     (push (buffer-substring (point) (mark)) keep))
   (forward-line))))
    (erase-buffer)
    (dolist (e (nreverse keep))
      (insert e "\n"))))

Aucun commentaire:

Enregistrer un commentaire