Vim Search and Replace — /, ?, :s, :%s Commands
Complete guide to searching and replacing text in Vim. Covers forward/backward search, search-under-cursor, substitute command, global replace, and confirmation mode.
Search/Replace
Detailed Explanation
Searching in Vim
Basic Search
| Command | Action |
|---|---|
/{pattern} |
Search forward for pattern |
?{pattern} |
Search backward for pattern |
n |
Go to next match (same direction) |
N |
Go to previous match (opposite direction) |
* |
Search forward for word under cursor |
# |
Search backward for word under cursor |
Search Options
| Setting | Effect |
|---|---|
:set ignorecase |
Case-insensitive search |
:set smartcase |
Case-sensitive only if pattern has uppercase |
:set hlsearch |
Highlight all matches |
:set incsearch |
Show matches as you type |
:noh |
Clear search highlighting |
Substitute (Replace) Command
The substitute command follows this pattern:
:[range]s/{pattern}/{replacement}/[flags]
Common Substitute Patterns
| Command | Scope |
|---|---|
:s/old/new/ |
First occurrence on current line |
:s/old/new/g |
All occurrences on current line |
:%s/old/new/g |
All occurrences in entire file |
:%s/old/new/gc |
All occurrences with confirmation |
:5,20s/old/new/g |
Lines 5 through 20 |
:'<,'>s/old/new/g |
Within visual selection |
Useful Flags
| Flag | Meaning |
|---|---|
g |
Global (all matches on the line, not just first) |
c |
Confirm each replacement |
i |
Case-insensitive |
I |
Case-sensitive |
n |
Count matches without replacing |
Advanced: Using Capture Groups
:%s/\(\w\+\) \(\w\+\)/\2 \1/g
This swaps two words separated by a space, using capture groups \1 and \2.
Use Case
You need to find text patterns in a file and optionally replace them, either globally or with manual confirmation for each match.