< Zurück | Inhalt | Weiter >

2.2.2 Search and Replace

We’ve mentioned searching for a string with / or ?, but what about replacing? Once you’ve located a string with /, you can use cw or C or R or other such commands to effect the change. Search for the next occurrence with n, and then you can repeat your change (the last c, s, r, and so on) by typing the period “.” that will repeat that last substitution, insert, and so on.

But what if you want to make 225 substitutions? Typing n.n.n.n.n.n. would get old after a while. Here, the ex mode, like any good command line, comes to the rescue to help with repetitive tasks.

If we want to search and replace all occurrences of one string for another, we can use the command

:1,$s/one string/another/

Almost all ex commands take an address range, that is, the lines of the file over which they will operate. If just one line number is given, the command will operate on that one line. Two numbers, separated by commas, represent the start and end lines—inclusive—of the operation. The first line is line 1, so a 0 as line number would mean “before the first line.” The line where the cursor is currently located is just “.” (a period). The last line of the file can be repre- sented by the dollar sign ($). You can even do some simple math on the addresses—for example, .+2 meaning the second line in front of the cursor’s current line.


There is a shortcut for the 1,$ address range. Use % to mean “all lines”—for example, %s/one string/another/.


Here are a few more substitution examples along with an explanation for each.


From here to the end of the file, replace here with eternity.


From line 27 to the 5th line prior to the end of the file, replace lost with



Replace here with now, on the current line only.

Each line that has a match will do the substitution on only the first occur- rence of the string. If you want to change all occurrences on those lines, you append a g (for “global” substitution) to the end of the command. Consider this snippet of Java:

class tryout


int tryout;

tryout(int startval) { // make a new tryout tryout = startval;

} // tryout constructor

// a tryout-like resetting public void

setTryout(int toval) { tryout = toval;


// willfindtryoutinhere

} // class tryout


Works as expected except for line 5, where “tryout” appears as the constructor name but also in the comment.


Works better (note the trailing g). But neither command can deal with “Tryout” in the setTryout method name. That’s because of the uppercase “T”, which doesn’t match “tryout”.


Will make the substitution in that method name.


Remember to precede these commands with a colon (“:”) to put you into ex mode which puts your cursor on the status bar of the window.