5.3. Saving and Exiting FilesYou have learned the vi command ZZ to quit and write (save) your file. But you will frequently want to exit a file using ex commands, because these commands give you greater control. We've already mentioned some of these commands in passing. Now let's take a more formal look.
vi protects existing files and your edits in the buffer. For example, if you want to write your buffer to an existing file, vi gives you a warning. Likewise, if you have invoked vi on a file, made edits, and want to quit without saving the edits, vi gives you an error message such as: No write since last change. These warnings can prevent costly mistakes, but sometimes you want to proceed with the command anyway. An exclamation point (!) after your command overrides the warning: :w! :q! :w! can also be used to save edits in a file that was opened in read-only mode with vi -R or view (assuming you have write permission for the file). :q! is an essential editing command that allows you to quit without affecting the original file, regardless of any changes you made in this session. The contents of the buffer are discarded. 5.3.1. Renaming the BufferYou can also use :w to save the entire buffer (the copy of the file you are editing) under a new filename. Suppose you have a file practice, which contains 600 lines. You open the file and make extensive edits. You want to quit but save both the old version of practice and your new edits for comparison. To save the edited buffer in a file called practice.new, give the command: :w practice.new Your old version, in the file practice, remains unchanged (provided that you didn't previously use :w). You can now quit editing the new version by typing :q. 5.3.2. Saving Part of a FileWhile editing, you will sometimes want to save just part of your file as a separate, new file. For example, you might have entered formatting codes and text that you want to use as a header for several files. You can combine ex line addressing with the write command, w, to save part of a file. For example, if you are in the file practice and want to save part of practice as the file newfile, you could enter:
5.3.3. Appending to a Saved FileYou can use the UNIX redirect and append operator (>>) with w to append all or part of the contents of the buffer to an existing file. For example, if you entered: :1,10w newfile then: :340,$w >>newfile newfile would contain lines 1-10 and from line 340 to the end of the buffer. Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|