vimtricks.wiki Concise Vim tricks, one at a time.

How do I delete all lines matching my last search pattern without retyping it?

Answer

:g//d

Explanation

:g//d uses an empty pattern in the global command, which instructs Vim to reuse the last search pattern. This creates a natural two-step workflow: search first to visually verify what will be deleted, then run :g//d to act on those same matches without retyping anything.

How it works

  • :g/pattern/d deletes all lines matching pattern
  • When the pattern is empty (:g//d), Vim substitutes the last search pattern used by /, ?, *, #, or :s
  • The same empty-pattern rule applies to :s//replacement/g, :v//d, :g//y A, and others

Example

Suppose you want to delete all debug logging lines:

1. Search to verify:   /console\.log
2. Review the highlighted matches in the buffer
3. Delete them all:    :g//d

Compare to the naive approach where you must type the pattern twice:

/console\.log
:g/console\.log/d

Tips

  • :v//d (or :g!//d) deletes all lines that do not match the last pattern — useful for keeping only matches
  • :g//y A collects all matching lines into register a (append)
  • :g//t$ copies all matching lines to the end of the file
  • After deletion, use :noh to clear search highlights while preserving the pattern in @/
  • Works after any search: *, #, n, or an explicit /pattern

Next

How do I mark and delete multiple files at once from within Vim's built-in file explorer netrw?