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

KeysWhat they do
:s/old/new/First match on this line
:s/old/new/gEvery match on this line
:%s/old/new/gEvery match in the file
:%s/old/new/gcEvery match, asking before each one
:5,12s/old/new/gOnly 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