Search and Replace in Vim
Essential Vim search and replace techniques that make text manipulation powerful and efficient once you understand how they work.
The Philosophy
Everything in Vim might seem to suck at first, but it sucks much less if you take the time to figure out how it works. Vim’s search and replace functionality is incredibly powerful once you master the basics.
Basic Search and Replace
Replace All Occurrences in Buffer
:%s/foo/bar/g
%- entire buffers- substitute commandfoo- search patternbar- replacement textg- global (all occurrences on each line)
Advanced Techniques
Replace Word Under Cursor
:%s/<C-r><C-w>/bar/g
<C-r><C-w>- inserts the word under cursor- Useful when you want to replace the current word throughout the file
Yank and Replace Word
viwy:%s/<C-r>"/bar/g
viwy- visually select inner word and yank<C-r>"- paste from default register- Perfect for replacing a word you’ve copied
Replace Last Searched Text
:%s//bar/g
- Empty search pattern uses the last search
- Great for replacing something you just searched for with
/
Replace with Last Yanked Text
:%s//\=@"/g
\=@"- expression replacement using default register- Replaces search pattern with whatever you last yanked
Practical Examples
Case-Insensitive Replace
:%s/foo/bar/gi
Add i flag for case-insensitive matching.
Replace in Selected Range
:10,20s/foo/bar/g
Replace only in lines 10-20.
Interactive Replace
:%s/foo/bar/gc
The c flag asks for confirmation on each replacement.
Replace with Line Numbers
:%s/^/\=line('.') . '. '/
Adds line numbers at the beginning of each line.
Register Usage
Vim’s registers make search and replace even more powerful:
"- default register (last yank/delete)0- yank register (last yank only)+- system clipboard/- last search pattern
Example with Specific Register
:%s//\=@0/g
Replace with content from yank register.
Tips and Tricks
- Preview changes: Use
:set hlsearchto highlight matches before replacing - Undo/Redo:
uto undo,<C-r>to redo - Visual selection: Select text first, then
:s///gapplies only to selection - Word boundaries: Use
\<and\>for exact word matching
Example with Word Boundaries
:%s/\<foo\>/bar/g
Only replaces complete words, not partial matches.
Why Vim’s Approach is Powerful
- Composable: Commands build on each other
- Repeatable:
.command repeats last action - Registers: Reuse content across operations
- Patterns: Full regex support for complex replacements
- Range-aware: Apply to specific line ranges
Once you understand these patterns, Vim’s search and replace becomes an incredibly efficient tool for text manipulation that far exceeds simple find-and-replace functionality in other editors.