Vim Text Editing Search and Replace Patterns

Search and Replace Patterns

AS
Aman Saurav
| Jan 22, 2025 |
5 min read
#regex #subsitution

Vim’s substitution command is fast and supports full regex.

Basic Syntax

:[range]s/pattern/replacement/flags

Examples

  • Replace first occurrence in current line:
    :s/foo/bar/
    
  • Replace all occurrences in current line:
    :s/foo/bar/g
    
  • Replace all occurrences in entire file (The most common one):
    :%s/foo/bar/g
    
    % is a shortcut for the range 1,$ (entire file). Use /gc flag to confirm each replacement (Compare Mode).

Advanced Pattern

Capture groups allow you to rearrange text. Example: Swap Firstname Lastname to Lastname, Firstname.

:%s/\(\w\+\) \(\w\+\)/\2, \1/g