Global replacements can be done with 2 ex commands in general: substitute and global.
:s/deprecated/new/
This substitute command simply replaces “deprecated” with “new” in the current line only one time.
:5,10s/deprecated/new/g
5,10 is a range and means “from lines 5 to 10″. Another range example is “0,$” meaning “from line 0 to the end of the file”. But this example can be written shorter: % means the whole content of the current file and so it can be used as an alias for “0,$”. The “g” at the end of the command means “global” and will make replacements any time the pattern matches. To approve each replacement, add an “c” (confirm) to “g”. Each line will be shown before the replacement will be done. Type “y” to accept an replacement and press Enter to get to the next match.
You have already learned a way to make replacements: Searches and macros. “/dep” will search for “dep” and “cwnew” will replace the word with “new”. Make the search again by typing “n”. Don’t forget the undo function: If anything fails, you can undo it by pressing “u” and redo it with “.”.
Sometime you only want to replace term by term in some special cases. For example “replace x with y only if line contains a”. In this case you need context-sensitive replacements. This is done with the global command:
:g/a/s/x/y/
So “:g” is the inital command. “a” is the term to match to select the line. “s” introduces a substition in this line and exactly “x” with “y”.
Recent Comments