Search and Replace
Searching for patterns and using the substitute command in Vim/Neovim.
Search
/pattern " Search forward
?pattern " Search backward
n " Next match
N " Previous match
* " Search for word under cursor (forward)
# " Search for word under cursor (backward)
:noh " Clear search highlighting
Search Options
:set ignorecase " Case insensitive search
:set smartcase " Case sensitive if pattern has uppercase
:set incsearch " Show matches as you type
:set hlsearch " Highlight all matches
Search Within Selection
To search only within a visual selection, use the \%V atom:
/\%Vpattern " Search for pattern only within last selection
- Make a visual selection
- Press
Escape(exits visual mode but remembers the selection) - Search with
/\%Vpattern
Replace
The substitute command (:s) is Vim’s powerful find and replace tool. It uses regular expressions to match patterns and replace them with new text.
Basic Syntax
:s/old/new/ " Replace first on current line
:s/old/new/g " Replace all on current line
:%s/old/new/g " Replace all in file
:%s/old/new/gc " Replace all with confirmation
:'<,'>s/old/new/g " Replace in visual selection
Flags
g " Global (all occurrences on line)
c " Confirm each replacement
i " Case insensitive
I " Case sensitive
Command Breakdown
The substitute command :%s/ \+/\t/g breaks down as:
| Part | Meaning |
|---|---|
: | Enter command mode |
% | Apply to all lines (without this, only affects current line) |
s | Substitute command |
/ | Delimiter separating parts |
\+ | Pattern: one or more spaces (\+ means “one or more”) |
/ | Delimiter |
\t | Replacement: a tab character |
/ | Final delimiter |
g | Flag: replace all matches on each line |
Range Examples
:s/old/new/ " Current line only, first match
:%s/old/new/g " All lines, all matches
:5,10s/old/new/g " Lines 5-10
:'<,'>s/old/new/g " Visual selection
:.,$s/old/new/g " Current line to end of file
:.,+5s/old/new/g " Current line and next 5 lines
Without g flag: Only replaces the first match on each line. Run multiple times to replace successive matches.
Replace Within Selection
When you make a visual selection and type :, Vim automatically inserts '<,'> to scope the command to the selection:
:'<,'>s/old/new/g " Replace within selected lines
To replace only within the visual selection (not entire lines), add the \%V atom:
:'<,'>s/\%Vold/new/g " Replace only within the selection bounds
This is useful for block selections (Ctrl-v) where you want to limit replacements to the selected columns.
Project-Wide Search and Replace
For replacing across multiple files, use the quickfix list with :cdo:
:grep pattern **/*.js " Populate quickfix with matches
:cdo s/old/new/g | update " Replace in each match and save
See also: Quickfix