start page | rating of books | rating of authors | reviews | copyrights

Unix Power ToolsUnix Power ToolsSearch this book

17.3. Editing Multiple Files with vi

ex commands enable you to switch between multiple files. The advantage is speed. When you are sharing the system with other users, it takes time to exit and re-enter vi for each file you want to edit. Staying in the same editing session and traveling between files is not only faster for access, but you also save abbreviations and command sequences that you have defined, and you keep yank buffers (Section 17.4) so that you can copy text from one file to another.

When you first invoke vi, you can name more than one file to edit and then use ex commands to travel between the files:

% vi file1 file2

This edits file1 first. After you have finished editing the first file, the ex command :w writes (saves) file1, and :n calls in the next file (file2). You can type :wn both to save the current file changes and to go to the next file. Typing :q! discards changes and closes the current file. Type vi * to edit all the files in a directory, though this will give you an error in some Unix systems. Type CTRL-g or :f to get the name of your current file; :args lists all filenames from the command line and puts brackets around the [current] file.

You can also switch at any time to another file not specified on the command line with the ex command :e. If you want to edit another file within vi, you first need to save your current file (:w), then you can type the following command:

:e filename

vi "remembers" two filenames at a time as the current and alternate filenames. These can be referred to by the symbols % (current filename) and # (alternate filename).

# is particularly useful with :e, since it allows you to switch back and forth between two files easily. The command :e# is always "switch to the other one." With different flavors of Unix, the vi command CTRL-^ (control-caret) is a synonym for :e#. This usually seems to work even without pressing the SHIFT key. For instance, if I get a caret by pressing SHIFT-6, I don't need to press CTRL-SHIFT-6 to make vi change files: just CTRL-6 is enough.

If you have not first saved the current file, vi will not allow you to switch files with :e or :n unless you tell it imperatively to do so by adding an exclamation point after the command.

The command:

:e!

is also useful. It discards your edits and returns to the last saved version of the current file.

In contrast to the # symbol, % is useful mainly in shell escapes (Section 17.21) and when writing out the contents of the current buffer to a new file. For example, you could save a second version of the file letter with the command:

:w %.new

instead of:

:w letter.new

-- LL and SP



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.