Search and Replace
Once you know the basics of editing, search is what makes Vim feel fast on real files instead of toy examples. It’s how you get across a 500-line file in three keystrokes instead of scrolling.
Searching
Press / followed by what you’re looking for, then Enter. Vim jumps to
the next match. Press n to jump to the next occurrence, N to jump to
the previous one. ? does the same thing but searches backward from your
cursor instead of forward.
Search wraps around the file by default, so if you search near the bottom and there are no more matches below, it loops back to the top.
A common pattern
Search first, then edit. If you want to delete the next occurrence of a
word, search for it with /word, land on it, then use dw or whatever
edit you need. This combination (search to navigate, then edit) is worth
noticing because it applies everywhere in Vim: motions get you somewhere,
operators act once you’re there.
Substitute: find and replace
The :s command does find-and-replace. The basic form is:
:s/old/new/
This replaces the first match on the current line. Add g at the end to
replace every match on the line:
:s/old/new/g
To act on the whole file instead of just the current line, prefix the
range with %:
:%s/old/new/g
That last one, %s/old/new/g, is probably the single most-used command
in all of Vim. It’s worth typing out a few times until your fingers know
it without thinking.
A little regex, carefully
The old part of :s/old/new/ can be a pattern, not just plain text.
:%s/cat.*dog/x/g matches “cat,” followed by anything, followed by
“dog.” You don’t need to learn Vim’s full regex dialect to be useful
today. Two things are enough for now:
.matches any single character*matches zero or more of whatever came before it
Everything else in Vim’s search patterns can wait until you actually need
it, at which point :help pattern will have the answer.
Confirming each replacement
If you’re not confident a blanket replace is safe, add c to the end of
the substitute command:
:%s/old/new/gc
Vim will stop at each match and ask you to confirm (y), skip (n), or
quit (q), so you can review before committing to hundreds of changes at
once.
Try it
Open a file with repeated words or phrases in it (or write one for this exercise) and practice:
- Search for a word with
/word, then pressna few times to step through the matches. - Search backward for the same word with
?word. - Replace the first occurrence of a word on one line with
:s/old/new/. - Replace every occurrence on one line with
:s/old/new/g. - Replace every occurrence in the whole file with
:%s/old/new/g. - Try
:%s/old/new/gcand step through the confirmation prompts, skipping at least one match on purpose to see hownbehaves.