Emacs: List Highlight Delete Matching Lines, Sort Reverse

By Xah Lee. Date: . Last updated: .

Alt+x occurAlt+s o】. It'll list all lines in the current file that matches a given text. Here's a sample output:

(list-matching-lines is alias of occur)

emacs list-matching-lines occur 2014
emacs list-matching-lines

Clicking the line will jump to the match location in the file.

If you want to match with word boundary, use \b, like this \bcat\b. This will find “cat” but not “cats”. [see Emacs: Regex Tutorial]

You can click on any matched line in the output, then emacs will put cursor at the position of the occurrence in your file.

There are also several other userful line processing commands:

  1. list-matching-lines (alias of occur)
  2. highlight-lines-matching-regexp
  3. delete-matching-lines (alias of flush-lines)
  4. delete-non-matching-lines (alias of keep-lines)
  5. delete-duplicate-lines (Emacs 24.4) delete duplicated lines in text selection.
  6. count-matches (alias of how-many)

and sort:

  1. sort-lines
  2. sort-numeric-fields
  3. reverse-region

If you use them often, you can give them an alias such as “sl” for sort-lines.

[see Emacs: Use Alias for Fast M-x]

Delete Starts at Cursor Position, or Text Selection

delete-matching-lines and delete-non-matching-lines starts at the line your cursor is on.

If you have a text selection, the deletion happens in the text selection only.

Escape Regex Chars

All these commands use regex to search. So, if you simply want to search plain words or phrases, and if your phrase contains any of regex characters, you need to escape them. Here's some commonly used regex characters that you'll need to place a backslash before it:

[ ] \ + * ? .

See also: common patterns in emacs regex.

Letter Case Sensitivity

In all these commands, if your search word contains upper case letters, then the search is automatically case sensitive. Otherwise, it is not case sensitive.

If you want case sensitive, Alt+x toggle-case-fold-search. Remember to toggle it back. Best to give a key.

List Lines in ALL Buffer

Alt+x multi-occur if you want to list lines in ALL buffers.

Emacs Find Replace

  1. Search Text in Buffer
  2. isearch Current Word
  3. Isearch Whitespace Regex
  4. Highlight Text in Buffer
  5. List Delete Highlight Sort Lines
  6. Search Text in Directory
  7. Find Replace in Buffer
  8. Find Replace in Directory
  9. xah-find.el, Find Replace in Pure Elisp
  10. Regex Tutorial

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs

Emacs

Emacs Lisp

Misc