Vim Scoops / Lessons / Find and replace
How to find and replace in Vim
Type :%s/old/new/g and press Enter to replace every old with new across the file. Leave off the % to change only the current line.
The keys
| Keys | What they do |
|---|---|
:s/old/new/ | First match on this line |
:s/old/new/g | Every match on this line |
:%s/old/new/g | Every match in the file |
:%s/old/new/gc | Every match, asking before each one |
:5,12s/old/new/g | Only lines 5 to 12 |
Read it left to right: % means every line and s means substitute. Then come the old text, the new text and any flags, split by slashes. g changes every match on a line, not just the first.
Select some lines with V and press :, and Vim fills in '<,'> so the change only touches your selection. If it goes wrong, one u undoes the whole lot.
Related
Want all of Vim, in order? Vim Scoops is a free game that starts at h j k l and builds up to macros.
Play the full game