Полезная информация

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 30.9 Using Search Patterns and Global CommandsChapter 30
vi Tips and Tricks
Next: 30.11 Keep Your Original File, Write to a New File
 

30.10 Confirming Substitutions in ex and vi

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 intended for 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! (30.4).

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

This command 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) 'vs 12 and press RETURN. If you don't want to make a change, simply press RETURN.

this can be used for invitations, signs, and menus.
   ^^^_

The combination of the vi commands, n (repeat last search) and dot (.) (repeat last command), is also an extraordinarily useful and quick way to page through a file and make repetitive changes that you may not want to make globally. So, for example, if your editor has told you that you're using which when you should be using that, you can spot-check every occurrence of which, changing only those that are incorrect:
/whichSearch for which.
cwthat [ESC]Change to that.
nRepeat search.
.Repeat change (if appropriate).
.
.
.
This often turns out to be faster than using a global substitution with confirmation. [It also lets you see other lines near the text you're checking. -JP ]

- DD, TOR


Previous: 30.9 Using Search Patterns and Global CommandsUNIX Power ToolsNext: 30.11 Keep Your Original File, Write to a New File
30.9 Using Search Patterns and Global CommandsBook Index30.11 Keep Your Original File, Write to a New File

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System