Skip to content
Vim

Search & Substitute

Find text with / and replace with :s, leveraging regex and ranges.

#search#substitute#regex

Code

vim
/foo                 " search forward for 'foo'
?foo                 " search backward
n / N                 " next / previous match
* / #                 " search word under cursor forward / backward
:set ignorecase      " case-insensitive search
:set smartcase       " case-sensitive when pattern has uppercase

" Substitute: :[range]s/pattern/replacement/flags
:s/old/new/          " replace first match on current line
:s/old/new/g         " replace all on current line
:%s/old/new/g        " replace in whole file
:%s/old/new/gc       " confirm each replacement
:5,20s/foo/bar/g     " replace in lines 5-20
:%s/\<word\>/TERM/g " match whole words only
:%s/\(foo\)\(bar\)/\2\1/g " swap groups using backrefs

" Magic: very-magic mode with \v reduces escaping
:%s/\v(\d+)/number \1/g