Quickly delete all lines containing a string

(defun kill-matching-lines-from-region-or-word ()
  "Kill all lines in the buffer that either the string in the active region or the word at point.

When called interactively:
- If a region is active, the text in the region becomes the literal string to search for.
- If no region is active, the function uses the word under the cursor.

All lines containing this strig or word will be deleted from the buffer, and the number of deleted lines is reported."
  (interactive)
  (let* ((string (if (use-region-p)
                     (buffer-substring-no-properties (region-beginning) (region-end))
                   (thing-at-point 'word)))
         (regexp (regexp-quote string))
         (count 0)
         (buffer-read-only nil)
         (inhibit-read-only t))
    (when string
      (save-excursion
        (goto-char (point-min))
        (while (re-search-forward regexp nil t)
          (let ((bol (save-excursion (beginning-of-line) (point)))
                (eol (save-excursion (end-of-line) (point))))
            (delete-region bol (min (1+ eol) (point-max)))
            (setq count (1+ count))
            ;; Move to the start of the next line if not at buffer end
            (unless (= (point) (point-max))
              (forward-line 0)))))
      (message "Deleted %d line%s containing \"%s\"" count (if (= count 1) "" "s") string))))

(global-set-key (kbd "M-2") 'kill-matching-lines-from-region-or-word)

Return to Home