Emacs copy/delete/count/sort (matching) line functions
Collection of ways to manipulate lines based off regex. All of these functions/tips were compiled from the links in Source.
1. Copy matching lines
(defun copy-lines-matching-re (re) "find all lines matching the regexp RE in the current buffer putting the matching lines in a buffer named *matching*" (interactive "sRegexp to match: ") (let ((result-buffer (get-buffer-create "*matching*"))) (with-current-buffer result-buffer (erase-buffer)) (save-match-data (save-excursion (goto-char (point-min)) (while (re-search-forward re nil t) (princ (buffer-substring-no-properties (line-beginning-position) (line-beginning-position 2)) result-buffer)))) (pop-to-buffer result-buffer)))
2. Count matching lines
(count-matches regexp)
3. Delete matching lines
(delete-matching-lines regexp) (delete-non-matching-lines regexp) ;; same as (keep-lines regexp) (keep-lines regexp) (delete-duplicate-lines regexp)
4. Sort lines
(sort-lines) (reverse-region) ;; separaters are spaces or tabs (sort-numeric-fields) (sort-fields)