Emacs: List/Delete Matching Lines, Sort Lines

By Xah Lee. Date: . Last updated: .
Alt+x list-matching-linesAlt+s o
List all lines in the current file that matches a given text. (alias of occur)
emacs list-matching-lines 2021-07-18
emacs list-matching-lines 2021-07-18

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]

Count Lines

Alt+x count-matches
Count matching lines. (alias of how-many)

Delete Matching Lines

Alt+x delete-matching-lines
Delete lines that match a regex. Works on text selection or starts at the line your cursor is on. (alias of flush-lines)
Alt+x delete-non-matching-lines
(alias of keep-lines)
Alt+x delete-duplicate-lines
Delete duplicated lines in text selection.

Sort Lines

Alt+x sort-lines
Sort lines in text selection.
Alt+x reverse-region
Reverse lines order in text selection.
Alt+x sort-numeric-fields
Sort lines by a specific column, as number. For example: Type Ctrl+u, then 2, then Alt+x sort-numeric-fields. This will sort the line by the 2nd column, and the fields are compared as numbers.
Alt+x sort-fields
Sort lines by a specific column, as string. (“fields” are separated by space or tabs. First field is 1.)

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.

List Lines in ALL Buffer

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

Emacs Find Replace

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys

ELisp

ELisp Examples

ELisp Write Major Mode


Emacs Tutorial

Quick Start

Manage Windows

File

Buffer

Find Replace

Copy/Paste

Unicode

Whitespace

Rectangle Edit

Line Wrap

Shell

View Special File

Working with Brackets

Org Mode

HTML

Emacs Efficiency

Misc