How do I search and replace text across an entire file?
Answer
:%s/old/new/g
Explanation
The :%s/old/new/g command replaces all occurrences of old with new across every line in the file.
How it works
:enters command-line mode%means "every line in the file"sis the substitute command/old/new/specifies the search pattern and replacementgflag means "all occurrences on each line" (without it, only the first match per line is replaced)
Example
Given the text:
foo bar foo
foo baz foo
Running :%s/foo/qux/g results in:
qux bar qux
qux baz qux
Tips
- Add
cflag for confirmation::%s/old/new/gcprompts before each replacement - Add
iflag for case-insensitive::%s/old/new/gi - Use
\<and\>for whole-word matching::%s/\<old\>/new/g - Replace only in a visual selection by selecting text first, then typing
:s/old/new/g