You have learned the vi
to quit and write
(save) your file.
But you will frequently want to exit a file using ex
these commands give you greater control. We've already
mentioned some of these commands in passing. Now let's take a
more formal look.
Writes (saves) the buffer to the file but does not exit.
You can (and should) use
throughout your editing
session to protect your edits against system failure or a major editing error.
Quits the editor (and returns to the UNIX prompt).
Both writes the file and quits the editor.
The write happens unconditionally, even if the file was not changed.
Both writes the file and quits (ex
the editor. The file is written only if it has been modified.[
protects existing files and your edits in the buffer.
For example, if you want to write your buffer to an existing file,
gives you a warning.
Likewise, if you have invoked vi
on a file,
and want to quit without
saving the edits, vi
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:
can also be used to save edits in a file that was opened
in read-only mode with
(assuming you have write permission for the file).
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.
You can also use
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
and your new edits for comparison.
To save the edited
buffer in a file called practice.new
, give the command:
Your old version, in the file practice
, remains unchanged
(provided that you didn't previously use
You can now quit editing the new version by typing
While 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,
, to save part of a file.
For example, if you are in the file
and want to save part of
as the file
, you could enter:
Saves from line 230 to end of file in newfile
Saves from the current line to line 600 in newfile
You can use the UNIX redirect and append operator (
to append all or part
of the contents of the buffer to an existing file.
For example, if you entered:
would contain lines 1-10 and from line 340 to the end
of the buffer.