6.1. Confirming Substitutions

It makes sense to be overly careful when using a search and replace command. It sometimes happens that what you get is not what you expect. You can undo any search and replacement command by entering u, provided that the command was the most recent edit you made. But you don't always catch undesired changes until it is too late to undo them. Another way to protect your edited file is to save the file with :w before performing a global replacement. Then at least you can quit the file without saving your edits and go back to where you were before the change was made. You can also read the previous version of the buffer back in with :e!.

It's wise to be cautious and know exactly what is going to be changed in your file. If you'd like to see what the search turns up and confirm each replacement before it is made, add the c option (for confirm) at the end of the substitute command:

:1,30s/his/the/gc

It will display the entire line where the string has been located, and the string will be marked by a series of carets (^^^^):

copyists at his school
                            ^^^_

If you want to make the replacement, you must enter y (for yes) and press RETURN. If you don't want to make a change, simply press RETURN.[1]

[1] elvis 2.0 doesn't support this feature. In the other clones, the actual appearance and prompt differ, but the effect is still the same, allowing you to choose whether or not to do the substitution in each case.

this can be used for invitations, signs, and ...

Get Learning the vi Editor, Sixth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.