How to Replace Text in Vim on Linux: Simple Guide
In Vim on Linux, you can replace text using the
:s command. For example, :s/old/new/g replaces all occurrences of 'old' with 'new' on the current line. To replace in the whole file, use :%s/old/new/g.Syntax
The basic syntax for replacing text in Vim is:
:s/old/new/flags- Replace 'old' with 'new' on the current line.:%s/old/new/flags- Replace in the entire file.flagscan begfor global (all occurrences),cto confirm each replacement.
Here, old is the text to find, new is the replacement text.
vim
:s/old/new/g :%s/old/new/g :%s/old/new/gc
Example
This example replaces all occurrences of 'apple' with 'orange' in the entire file without confirmation.
vim
:%s/apple/orange/g
Common Pitfalls
Common mistakes include:
- Forgetting the
%to apply replacement to the whole file, which limits changes to the current line only. - Not using the
gflag, so only the first occurrence on each line is replaced. - Not escaping special characters in the search or replacement text.
Example of wrong and right usage:
vim
:s/apple/orange :s/apple/orange/g
Quick Reference
| Command | Description |
|---|---|
| :s/old/new/ | Replace first occurrence on current line |
| :s/old/new/g | Replace all occurrences on current line |
| :%s/old/new/ | Replace first occurrence in whole file |
| :%s/old/new/g | Replace all occurrences in whole file |
| :%s/old/new/gc | Replace all with confirmation in whole file |
Key Takeaways
Use :s/old/new/g to replace all occurrences on the current line.
Add % before s to replace throughout the entire file, like :%s/old/new/g.
Use the g flag to replace all matches on a line, not just the first.
Use the c flag to confirm each replacement interactively.
Escape special characters in search or replacement text to avoid errors.