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). On many versions of vi, 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).
: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