Skip to content
Vim

Search & Substitute

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

By EZ4Code Team
searchsubstituteregex

Code

/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

Explanation

/ searches forward, ? backward; n/N repeat. * grabs the word under the cursor. :s performs substitution with the form :range/s/pat/rep/flags — g means all-per-line (not just first), c confirms each, i ignores case. % is the whole-file range. Vim regex is 'magic' by default: () need escaping to group; use \v (very-magic) to make () and + behave like PCRE. Backreferences are \1, \2... Use :set ignorecase + smartcase for sane case handling.

More Vim Snippets