Search and Replace Patterns
AS
Aman Saurav
5 min read
#regex
#subsitution
Vim’s substitution command is fast and supports full regex.
Basic Syntax
:[range]s/pattern/replacement/flags
Examples
- Replace first occurrence in current line:
:s/foo/bar/ - Replace all occurrences in current line:
:s/foo/bar/g - Replace all occurrences in entire file (The most common one):
:%s/foo/bar/g%is a shortcut for the range1,$(entire file). Use/gcflag to confirm each replacement (Compare Mode).
Advanced Pattern
Capture groups allow you to rearrange text.
Example: Swap Firstname Lastname to Lastname, Firstname.
:%s/\(\w\+\) \(\w\+\)/\2, \1/g