How to do a global search & replace in vi


:1,$s/searchstring/replacestring/g

The 1,$ means do the following command for lines 1 through the last line of the file. The g at the end means do it for all occurrences on a line, not just the first. If you want a confirmation prompt before each replacement, add a c after the g, like so:

:1,$s/searchstring/replacestring/gc

To confirm a substitution, type y and then Enter when prompted.

As another example, let's say you have the following lines in a file that you're editing:

fakeroot:*:0:3:Admin root ID for mortals:/home/fakeroot:/sbin/sh
daemon:*:1:5::/:/sbin/sh
bin:*:2:2::/usr/bin:/sbin/sh
sys:*:3:3::/:
adm:*:4:4::/var/adm:/sbin/sh
uucp:*:5:3::/var/spool/uucppublic:/usr/lbin/uucp/uucico
lp:*:9:7::/var/spool/lp:/sbin/sh

If you want to insert TT at the beginning of each line, use this:

:%s/^/TT/

The % means the same as 1,$, and the ^ means the beginning of the line. Now the above will look like this:

TTfakeroot:*:0:3:Admin root ID for mortals:/home/fakeroot:/sbin/sh
TTdaemon:*:1:5::/:/sbin/sh
TTbin:*:2:2::/usr/bin:/sbin/sh
TTsys:*:3:3::/:
TTadm:*:4:4::/var/adm:/sbin/sh
TTuucp:*:5:3::/var/spool/uucppublic:/usr/lbin/uucp/uucico
TTlp:*:9:7::/var/spool/lp:/sbin/sh

To do the opposite, to remove the TT from the beginning of each line, run

:%s/^TT//

To insert TT at the beginning of the current line and the following three lines (for a total of four lines) run this:

:.,+3s/^/TT/

12/22/2003