亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区

Chinaunix

標(biāo)題: 《Learning the vi editor》 [打印本頁(yè)]

作者: projl    時(shí)間: 2008-06-11 13:08
標(biāo)題: 《Learning the vi editor》
Chapter 1. The vi Text Editor
UNIX has a number of editors that can process the contents of text
files, whether those files contain data, source code, or sentences.
There are line editors, such as ed and ex, which display a line of the
file on the screen; and there are screen editors, such as vi and
emacs, which display a part of the file on your terminal screen. Text
editors based on the X Window System are also commonly
available, and are becoming increasing popular. Both GNU emacs
and its derivative xemacs provide multiple X windows; an
interesting alternative is the sam editor from Bell Labs. All but one
of the vi clones described in Part II of this book also provide X-
based interfaces.

vi is the most useful standard text editor on your system. (vi is
short for visual editor and is pronounced "vee-eye.") Unlike emacs,
it is available in nearly identical form on almost every UNIX system,

[1]
thus providing a kind of text-editing lingua franca. The same might
be said of ed and ex, but screen editors are generally much easier
to use. With a screen editor, you can scroll the page, move the
cursor, delete lines, insert characters, and more, while seeing the
results of your edits as you make them. Screen editors are very
popular, since they allow you to make changes as you read through
a file, like you would edit a printed copy, only faster.

[1] Actually, these days, GNU emacs is pretty much the universal version of emacs; the only problem is it
doesn't come standard with most commercial UNIX systems; you must retrieve and install it yourself.
To many beginners, vi looks unintuitive and cumbersome鈥攊nstead
of using special control keys for word processing functions and just
letting you type normally, it uses all of the regular keyboard keys
for issuing commands. When the keyboard keys are issuing
commands, vi is said to be in command mode. You must be in a
special insert mode before you can type actual text on the screen.
In addition, there seem to be so many commands.

Once you start learning, however, you realize that vi is well
designed. You need only a few keystrokes to tell vi to do complex
tasks. As you learn vi, you learn shortcuts that transfer more and
more of the editing work to the computer鈥攚here it belongs.

vi (like any text editor) is not a "what you see is what you get" word
processor. If you want to produce formatted documents, you must
type in codes that are used by another formatting program to
control the appearance of the printed copy. If you want to indent
several paragraphs, for instance, you put a code where the indent
begins and ends. Formatting codes allow you to experiment with or

[ 本帖最后由 projl 于 2008-6-12 16:59 編輯 ]

vi.pdf

1.9 MB, 下載次數(shù): 6437


作者: projl    時(shí)間: 2008-06-11 13:10
change the appearance of your printed files, and in many ways,
give you much more control over the appearance of your
documents than a word processor. UNIX supports the troff
formatting package.[2] The and formatters are popular, commonly
available alternatives.

[2] troff is for laser printers and typesetters. Its "twin brother" is nroff, for line printers and terminals. Both
accept the same input language. Following common UNIX convention, we refer to both with the name troff.
(vi does support some simple formatting mechanisms. For example,
you can tell it to automatically wrap when you come to the end of a
line, or to automatically indent new lines.)

As with any skill, the more editing you do, the easier the basics
become, and the more you can accomplish. Once you are used to all
the powers you have while editing with vi, you may never want to
return to any "simpler" editor.

What are the components of editing? First, you want to insert text
(a forgotten word or a missing sentence), and you want to delete
text (a stray character or an entire paragraph). You also need to
change letters and words (to correct misspellings or to reflect a
change of mind about a term). You might want to move text from
one place to another part of your file. And, on occasion, you want to
copy text to duplicate it in another part of your file.

Unlike many word processors, vi's command mode is the initial or
"default" mode. Complex, interactive edits can be performed with
only a few keystrokes. (And to insert raw text, you simply give any
of the several "insert" commands and then type away.)

One or two characters are used for the basic commands. For
example:

insert

cw

change word

Using letters as commands, you can edit a file with great speed.
You don't have to memorize banks of function keys or stretch your
fingers to reach awkward combinations of keys. Most of the
commands can be remembered by the letter that performs them,
and nearly all commands follow similar patterns and are related to
each other.
作者: projl    時(shí)間: 2008-06-11 13:11
In general, vi commands:


  * Are case-sensitive (uppercase and lowercase keystrokes mean
different things; I is different from i).

  * Are not shown (or "echoed") on the screen when you type
them.

  *Do not require a RETURN after the command.

There is also a group of commands that echo on the bottom line of
the screen. Bottom-line commands are preceded by different
symbols. The slash (/) and the question mark (?) begin search
commands, and are discussed in Chapter 3. A colon (:) begins all
ex commands. ex commands are those that are used by the ex line
editor. The ex editor is available to you when you use vi, because
ex is the underlying editor, and vi is really just its "visual" mode. ex
commands and concepts are discussed fully in Chapter 5, but this
chapter introduces you to the ex commands to quit a file without
saving edits.

1.1 Opening and Closing Files
You can use vi to edit any text file. vi copies the file to be edited
into a buffer (an area temporarily set aside in memory), displays
the buffer (though you can see only one screenful at a time), and
lets you add, delete, and change text. When you save your edits, vi
copies the edited buffer back into a permanent file, replacing the old
file of the same name. Remember that you are always working on a
copy of your file in the buffer, and that your edits will not affect
your original file until you save the buffer. Saving your edits is also
called "writing the buffer," or more commonly, "writing your file."

1.1.1 Opening a File
vi is the UNIX command that invokes the vi editor for an
existing file or for a brand new file. The syntax for the vi command
is:

$ vi [filename ]

The brackets shown on the above command line indicate that the
filename is optional. The brackets should not be typed. The $ is the
UNIX prompt. If the filename is omitted, vi will open an unnamed
buffer. You can assign the name when you write the buffer into a
file. For right now, though, let's stick to naming the file on the
command line.

[[i] 本帖最后由 projl 于 2008-6-11 13:28 編輯 [/i]]
作者: projl    時(shí)間: 2008-06-11 13:11
A filename must be unique inside its directory. On older System V
UNIX systems, it cannot exceed 14 characters in length (most
common UNIX systems allow much longer names). A filename can
include any 8-bit character except a slash (/), which is reserved as
the separator between files and directories in a pathname, and
ASCII NUL, the character with all zero bits. You can even include
spaces in a filename by typing a backslash (\) before the space. In
practice, though, filenames generally consist of any combination of
uppercase and lowercase letters, numbers, and the characters dot
(.) and underscore (_). Remember that UNIX is case-sensitive:
lowercase letters are distinct from uppercase letters. Also remember
that you must press RETURN to tell UNIX that you are finished
issuing your command.

When you want to open a new file in a directory, give a new
filename with the vi command. For example, if you want to open a
new file called practice in the current directory, you would enter:

$ vi practice

Since this is a new file, the buffer is empty and the screen appears
as follows:

~
~
~
"practice" [New file].

The tildes (~) down the left-hand column of the screen indicate that
there is no text in the file, not even blank lines. The prompt line
(also called the status line) at the bottom of the screen echoes the
name and status of the file.

You can also edit any existing text file in a directory by specifying
its filename. Suppose that there is a UNIX file with the pathname
/home/john/letter. If you are already in the /home/john directory,
use the relative pathname. For example:

$ vi letter

brings a copy of the file letter to the screen.

If you are in another directory, give the full pathname to begin
editing:

$ vi /home/john/letter
作者: projl    時(shí)間: 2008-06-11 13:12
1.1.2 Problems Opening Files

* When you invoke vi, the message [open mode] appears.

Your terminal type is probably incorrectly identified. Quit the
editing session immediately by typing :q. Check the
environment variable $TERM. It should be set to the name of
your terminal. Or ask your system administrator to provide an
adequate terminal type setting.

* You see one of the following messages:

* Visual needs addressable cursor or uplinecapability

* Bad termcap entry

* Termcap entry too long

* terminal: Unknown terminal type

*Block device requiredNot a typewriter

Your terminal type is either undefined, or there's probably
something wrong with your terminfo or termcap entry. Enter
:q to quit. Check your $TERM environment variable, or ask
your system administrator to select a terminal type for your
environment.

*A [new file] message appears when you think a file already
exists.

You are probably in the wrong directory. Enter :q to quit.
Then check to see that you are in the correct directory for
that file (enter pwd at the UNIX prompt). If you are in the
right directory, check the list of files in the directory (with ls)
to see whether the file exists under a slightly different name.

* You invoke vi, but you get a colon prompt (indicating that
you're in ex line-editing mode).

You probably typed an interrupt before vi could draw the
screen. Enter vi by typing vi at the ex prompt (:).

* One of the following messages appears:

* [Read only]

* File is read onlyPermission denied
"Read only" means that you can only look at the file; you
cannot save any changes you make. You may have invoked vi

[ 本帖最后由 projl 于 2008-6-11 13:30 編輯 ]
作者: projl    時(shí)間: 2008-06-11 13:13
in view mode (with view or vi -R), or you do not have write
permission for the file. See Section 1.2.1 below.


One of the following messages appears:
Bad file number

Block special fileCharacter special fileDirectoryExecutable

Non-ascii file

file non-ASCII

The file you've called up to edit is not a regular text file. Type
:q! to quit, then check the file you wish to edit, perhaps with
the file command.


When you type :q because of one of the above difficulties, the
message appears:
No write since last change (:quit! overrides).

You have modified the file without realizing it. Type :q! to

leave vi. Your changes from this session will not be saved in

the file.

1.1.3 Modus Operandi
As mentioned earlier, the concept of the current "mode" is
fundamental to the way vi works. There are two modes, command
mode and insert mode. You start out in command mode, where
every keystroke represents a command. In insert mode, everything
you type becomes text in your file.

Sometimes, you can accidentally enter insert mode, or conversely,
leave insert mode accidentally. In either case, what you type will
likely affect your files in ways you did not intend.

Press the ESC key to force vi to enter command mode. If you are
already in command mode, vi will beep at you when you press the
ESC key. (Command mode is thus sometimes referred to as "beep
mode.")

Once you are safely in command mode, you can proceed to repair
any accidental changes, and then continue editing your text.

[ 本帖最后由 projl 于 2008-6-11 13:33 編輯 ]
作者: projl    時(shí)間: 2008-06-11 13:13
1.1.4 Saving and Quitting a File
You can quit working on a file at any time, save your edits and
return to the UNIX prompt. The vi command to quit and save edits
is ZZ. Note that ZZ is capitalized.

Let's assume that you do create a file called practice to practice vi
commands, and that you type in six lines of text. To save the file,
first check that you are in command mode by pressing ESC and
then enter ZZ.

Keystrokes Results
ZZ
Give the write and save command, ZZ. Your file is saved as a regular
UNIX file.
ls
Listing the files in the directory shows the new file practice that you
created.

You can also save your edits with ex commands. Type :w to save
your file but not quit vi; type :q to quit if you haven't made any
edits; and type :wq to both save your edits and quit. (:wq is
equivalent to ZZ.) We'll explain fully how to use commands in
Chapter 5, Introducing the ex Editor; for now, you should just
memorize a few commands for writing and saving files.

1.2 Quitting Without Saving Edits
When you are first learning vi, especially if you are an intrepid
experimenter, there are two other ex commands that are handy for
getting out of any mess that you might create.

What if you want to wipe out all of the edits you have made in a
session and then return to the original file? The command:

:e! RETURN

returns you to the last saved version of the file, so you can start
over.

Suppose, however, that you want to wipe out your edits and then
just quit vi? The command:

:q! RETURN
作者: projl    時(shí)間: 2008-06-11 13:14
quits the file you're editing and returns you to the UNIX prompt.
With both of these commands, you lose all edits made in the buffer
since the last time you saved the file. vi normally won't let you
throw away your edits. The exclamation point added to the :e or :qcommand causes vi to override this prohibition, performing the
operation even though the buffer has been modified.

1.2.1 Problems Saving Files

You try to write your file, but you get one of the following
messages:

File exists

File file exists - use w!

[Existing file]
File is read only
Type :w! file to overwrite the existing file, or type :w
newfile to save the edited version in a new file.

You want to write a file, but you don't have write permission
for it. You get the message "Permission denied."
Use :w newfile to write out the buffer into a new file. If you
have write permission for the directory, you can use mv to
replace the original version with your copy of it. If you don't
have write permission for the directory, type :w
pathname/file to write out the buffer to a directory in which
you do have write permission (such as your home directory,
or /tmp).


You try to write your file, but you get a message telling you
that the file system is full.
Type :!rm junkfile to delete a (large) unneeded file and free
some space. (Starting an ex command with an exclamation
point gives you access to UNIX.)

Or type :!df to see whether there's any space on another file
system. If there is, choose a directory on that file system and
write your file to it with :w pathname. (df is the UNIX
command to check a disk's free space.)


The system puts you into open mode and tells you that the
file system is full.
The disk with vi's temporary files is filled up. Type :!ls /tmpto see whether there are any files you can remove to gain

[ 本帖最后由 projl 于 2008-6-11 13:31 編輯 ]
作者: projl    時(shí)間: 2008-06-11 13:14
some disk space.[3] If there are, create a temporary UNIX shell
from which you can remove files or issue other UNIX
commands. You can create a shell by typing :sh; type CTRL-D
or exit to terminate the shell and return to vi. (On most UNIX
systems, when using a job-control shell, you can simply type
CTRL-Z to suspend vi and return to the UNIX prompt; type fgto return to vi.) Once you've freed up some space, write your
file with :w!.

[3] Your vi may keep its temporary files in /usr/tmp, /var/tmp, or your current directory; you may
need to poke around a bit to figure out where exactly you've run out of room.

You try to write your file, but you get a message telling you
that your disk quota has been reached.
Try to force the system to save your buffer with the ex
command :pre (short for :preserve). If that doesn't work,
look for some files to remove. Use :sh (or CTRL-Z if you are
using a job-control system) to move out of vi and remove
files. Use CTRL-D (or fg) to return to vi when you're done.
Then write your file with :w!.

1.2.2 Exercises
The only way to learn vi is to practice. You now know enough to
create a new file and to return to the UNIX prompt. Create a file
called practice, insert some text, and then save and quit the file.

Open a file called practice in the current directory: vi practice
Insert text: i any text you like
Return to command mode: ESC
Quit vi, saving edits: ZZ

[ 本帖最后由 projl 于 2008-6-11 13:31 編輯 ]
作者: projl    時(shí)間: 2008-06-11 13:15
Chapter 2. Simple Editing

This chapter introduces you to editing with vi, and it is set up to be
read as a tutorial. In it you will learn how to move the cursor and
how to make some simple edits. If you've never worked with vi, you
should read the entire chapter.

Later chapters show you how to expand your skills to perform faster
and more powerful edits. One of the biggest advantages for an
adept user of vi is that there are so many options to choose from.
(One of the biggest disadvantages for a newcomer to vi is that there
are so many different editor commands.)

You can't learn vi by memorizing every single vi command. Start
out by learning the basic commands introduced in this chapter. Note
the patterns of use that the commands have in common.

As you learn vi, be on the lookout for more tasks that you can
delegate to the editor, and then find the command that
accomplishes it. In later chapters you will learn more advanced
features of vi, but before you can handle the advanced, you must
master the simple.

This chapter covers:

Moving the cursor

Adding and changing text

Deleting, moving, and copying text

More ways to enter insert mode

2.1 vi Commands
vi has two modes: command mode and insert mode. As soon as you
enter a file, you are in command mode, and the editor is waiting for
you to enter a command. Commands enable you to move anywhere
in the file, to perform edits, or to enter insert mode to add new
text. Commands can also be given to exit the file (saving or
ignoring your edits) in order to return to the UNIX prompt.

You can think of the different modes as representing two different
keyboards. In insert mode, your keyboard functions like a
typewriter. In command mode, each key has a new meaning or
initiates some instruction.


There are several ways to tell vi that you want to begin insert
mode. One of the most common is to press i. The i doesn't appear

[ 本帖最后由 projl 于 2008-6-11 13:32 編輯 ]
作者: projl    時(shí)間: 2008-06-11 13:16
on the screen, but after you press it, whatever you type will appear
on the screen and will be entered into the buffer. The cursor marks
the current insertion point. To tell vi that you want to stop inserting
text, press ESC. Pressing ESC moves the cursor back one space (so
that it is on the last character you typed) and returns vi to
command mode.

For example, suppose you have opened a new file and want to
insert the word "introduction". If you type the keystrokes
iintroduction, what appears on the screen is:

introduction

When you open a new file, vi starts in command mode and
interprets the first keystroke (i) as the insert command. All
keystrokes made after the insert command are considered text until
you press ESC. If you need to correct a mistake while in insert
mode, backspace and type over the error. Depending on the type of
terminal you are using, backspacing may erase what you've
previously typed or may just back up over it. In either case,
whatever you back up over will be deleted. Note that you can't use
the backspace key to back up beyond the point where you entered
insert mode.

vi has an option that lets you define a right margin and provides a
carriage return automatically when you reach it. For right now,
while you are inserting text, press RETURN to break the lines.

Sometimes you don't know whether you are in insert mode or
command mode. Whenever vi does not respond as you expect,
press ESC once or twice to check which mode you are in. When you
hear the beep, you are in command mode.

2.2 Moving the Cursor
You may spend only a small amount of time in an editing session
adding new text in insert mode; much of the time you will be
making edits to existing text.

In command mode you can position the cursor anywhere in the file.
Since you begin all basic edits (changing, deleting, and copying
text) by placing the cursor at the text that you want to change, you
want to be able to move the cursor to that place as quickly as
possible.

There are vi commands to move the cursor:


作者: projl    時(shí)間: 2008-06-11 13:16

作者: projl    時(shí)間: 2008-06-11 13:17
Before you move the cursor, press ESC to make sure that you are in
command mode. Use h, j, k, and l to move forward or backward in
the file from the current cursor position. When you have gone as far
as possible in one direction, you hear a beep and the cursor stops.
For example, once you're at the beginning or end of a line, you
cannot use h or l to wrap around to the previous or next line; you

[1]
have to use j or k. Similarly, you cannot move the cursor past a
tilde (~) representing a line without text, nor can you move the
cursor above the first line of text.

[1] vim version 4.x, and vim version 5.x with nocompatible set, allow you to "space past" the end of the line
to the next one with l or the spacebar.
2.2.2 Numeric Arguments
You can precede movement commands with numbers. Figure 2.2
shows how the command 4l moves the cursor four spaces to the
right, just as if you had typed l four times (llll).

Figure 2.2. Multiplying commands by numbers


The ability to multiply commands gives you more options and power
for each command you learn. Keep it in mind as you are introduced
to additional commands.

2.2.3 Movement Within a Line
When you saved the file practice, vi displayed a message telling you
how many lines are in that file. A line is not necessarily the same
length as the visible line (often limited to 80 characters) that
appears on the screen. A line is any text entered between newlines.
(A newline character is inserted into the file when you press the
RETURN key in insert mode.) If you type 200 characters before
pressing RETURN, vi regards all 200 characters as a single line
(even though those 200 characters visibly take up several lines on
the screen).

As we mentioned, vi has an option that allows you to set a distance
from the right margin at which vi will automatically insert a newline
character. This option is wrapmargin (its abbreviation is wm). You
can set a wrapmargin at 10 characters:

:set wm=10
作者: projl    時(shí)間: 2008-06-11 13:17
This command doesn't affect lines that you've already typed. We'll
talk more about setting options in Chapter 7. (This one really
couldn't wait!)

If you do not use vi's automatic wrapmargin option, you should
break lines with carriage returns to keep the lines of manageable
length.


Two useful commands that involve movement within a line are:

Move to beginning of line.

$

Move to end of line.

In the example below, line numbers are displayed. (Line numbers
can be displayed in vi by using the number option, which is enabled
by typing :setnu in command mode. This operation is described in
Chapter 7.)


The number of logical lines (3) does not correspond to the
number of visible lines (6) that you see on the screen. If the cursor
were positioned on the d in the word delete, and you entered $, the
cursor would move to the period following the word them. If you
entered 0, the cursor would move back to the letter m in the word
move, at the beginning of line two.
作者: projl    時(shí)間: 2008-06-11 13:18
2.2.4 Movement by Text Blocks
You can also move the cursor by blocks of text: words,
sentences, paragraphs, etc. The w command moves the cursor
forward one word at a time, counting symbols and punctuation as
equivalent to words. The line below shows cursor movement by w:

cursor, delete lines, insert characters,

You can also move by word, not counting symbols and punctuation,
using the W command. (You can think of this as a "large" or "capital"
Word.)

Cursor movement using W looks like this:

cursor, delete lines, insert characters,

To move backward by word, use the b command. Capital B allows
you to move backward by word, not counting punctuation.

As mentioned previously, movement commands take numeric
arguments; so, with either the w or b commands you can multiply
the movement with numbers. 2w moves forward two words; 5B
moves back five words, not counting punctuation.

We'll discuss movement by sentences and by paragraphs in Chapter

3. For now, practice using the cursor movement commands that you
know, combining them with numeric multipliers.
2.3 Simple Edits
When you enter text in your file, it is rarely perfect. You find typos
or want to improve on a phrase; sometimes your program has a
bug. Once you enter text, you have to be able to change it, delete
it, move it, or copy it. Figure 2.3 shows the kinds of edits you might
want to make to a file. The edits are indicated by proofreading
marks.

Figure 2.3. Proofreading edits
作者: projl    時(shí)間: 2008-06-11 13:18
In vi you can perform any of these edits with a few basic
keystrokes: i for insert (which you've already seen); a for append;
c for change; and d for delete. To move or copy text, you use a pair
of commands. You move text with a d for delete, then a p for put;
you copy text with a y for "yank," then a p for put. Each type of edit
is described in this section. Figure 2.4 shows the vi commands you
use to make the edits marked in Figure 2.3.

Figure 2.4. Edits with vi commands


2.3.1 Inserting New Text
You have already seen the insert command used to enter text into a
new file. You also use the insert command while editing existing
text to add missing characters, words, and sentences. In the file
practice, suppose you have the sentence:
作者: projl    時(shí)間: 2008-06-11 13:19
with the cursor positioned as shown. To insert With a screen editor
at the beginning of the sentence, enter the following:

Keystrokes Results
2k
Move the cursor up two lines with the k command, to the line
where you want to make the insertion.
iWith a
Press i to enter insert mode and begin inserting text.
screen
editorESC
Finish inserting text, and press ESC to end the insert and return to
command mode.

On the screen shown in the example above, vi pushes existing text
to the right as the new text is inserted. That is because we are
assuming that you are using vi on an "intelligent" terminal that can
rewrite the screen with each character you type. An insert on a
"dumb" terminal (such as an adm3a) will look different. The
terminal itself cannot handle the overhead of updating the screen
for each character typed (without a tremendous sacrifice of speed),
so vi doesn't rewrite the screen until after you press ESC. On a
dumb terminal, the same insert would appear:

Keystrokes Result
iWith a
Press i to enter insert mode and begin inserting text. The dumb
terminal appears to overwrite the existing text on the line.
screen
editor
The insertion appears to have overwritten existing text.
ESC
作者: projl    時(shí)間: 2008-06-11 13:20
After you have finished inserting text, press ESC to end the insert and
return to command mode. vi now rewrites the line, so that you see all
existing text.

2.3.2 Appending Text
You can append text at any place in your file with the append
command a. a works in almost the same way as i, except that text
is inserted after the cursor rather than before the cursor. You may
have noticed that when you press i to enter insert mode, the cursor
doesn't move until after you enter some text. On the other hand,
when you press a to enter insert mode, the cursor moves one space
to the right. When you enter text, it appears after the original
cursor position.

2.3.3 Changing Text
You can replace any text in your file with the change command,

c. In order to tell c how much text to change, you combine c with a
movement command. In this way, a movement command serves as
a text object for the c command to affect. For example, c can be
used to change text from the cursor:
cw

to the end of a word.

c2b

back two words

c$

to the end of line

c0

to the beginning of line.

After issuing a change command, you can replace the identified text
with any amount of new text, with no characters at all, with one
word, or with hundreds of lines. c, like i and a, leaves you in insert
mode until you press the ESC key.
作者: projl    時(shí)間: 2008-06-11 13:20
When the change only affects the current line, vi marks the end of
the text that will be changed with a $, so that you can see what part
of the line is affected. (See the example for cw, below.)

2.3.3.1 Words
To change a word, combine the c (change) command with w
for word. You can replace a word (cw) with a longer or shorter word
(or any amount of text). cw can be thought of as "delete the word
marked and insert new text until ESC is pressed."

Suppose you have the following line in your file practice:

With an editor you can scroll the page,

and want to change an to a screen. You need to change only one
word:

Keystrokes Results
w
Move with w to the place you want the edit to begin.
cw
Give the change word command. The end of the text to be changed will
be marked with a $ (dollar sign).
a
screen Type in the replacement text, and then press ESC to return to
command mode.

cw also works on a portion of a word. For example, to change
spelling to spelled, you can position the cursor on the i, type cw,
then type ed, and finish with ESC.

General Form of vi Commands

In the change commands we've mentioned up to this point,
you may have noticed the following pattern:
(command)(text object)
command is the change command c, and text object is
a
作者: projl    時(shí)間: 2008-06-11 13:21
movement command (you don't type the parentheses). But c
is not the only command that requires a text object. The d
command (delete) and the y command (yank) follow this
pattern as well.

Remember also that movement commands take numeric
arguments, so numbers can be added to the text objects of
c, d, and y commands. For example, d2w and 2dw are
commands to delete two words. With this in mind, you can
see that most vi commands follow a general pattern:

(command)(number)(text object)

or the equivalent form:

(number)(command)(text object)

Here's how this works. number and command are optional.
Without them, you simply have a movement command. If
you add a number, you have a multiple movement. On the
other hand, combine a command (c, d, or y) with a text
object to get an editing command.

When you realize how many combinations are possible in this
way, vi becomes a powerful editor indeed!

2.3.3.2 Lines
To replace the entire current line, there is the special change
command, cc. cc changes an entire line, replacing that line with
any amount of text entered before pressing ESC. It doesn't matter
where the cursor is located on the line; cc replaces the entire line of
text.

A command like cw works differently from a command like cc. In
using cw, the old text remains until you type over it, and any old
text that is left over (up to the $) goes away when you press ESC.
In using cc, though, the old text is wiped out first, leaving you a
blank line on which to insert text.

The "type over" approach happens with any change command that
affects less than a whole line, whereas the "blank line" approach
happens with any change command that affects one or more lines.
作者: projl    時(shí)間: 2008-06-11 13:21
C replaces characters from the current cursor position to the end
of the line. It has the same effect as combining c with the special
end-of-line indicator $ (c$).

The commands cc and C are really shortcuts for other commands,
so they don't follow the general form of vi commands. You'll see
other shortcuts when we discuss the delete and yank commands.

2.3.3.3 Characters
One other replacement edit is given by the r command. r
replaces a single character with another single character. You do
not have to press ESC to return to command mode after making the
edit. There is a misspelling in the line below:


Only one letter needs to be corrected. You don't want to use cw in
this instance because you would have to retype the entire word. Use
r to replace a single character at the cursor:

Keystrokes

Results

rW


Give the replace command r, followed by the replacement character W.

2.3.3.4 Substituting text
Suppose you want to change just a few characters, and not a
whole word. The substitute command (s), by itself, replaces a single
character. With a preceding count, you can replace that many
characters. As with the change command (c), the last character of
the text will be marked with a $ so that you can see how much text
will be changed.


The S command, as is usually the case with uppercase
commands, lets you change whole lines. In contrast to the C
command, which changes the rest of the line from the current
cursor position, the S command deletes the entire line, no matter
where the cursor is. vi puts you in insert mode at the beginning of
the line. A preceding count replaces that many lines.
作者: projl    時(shí)間: 2008-06-11 13:22
Both s and S put you in insert mode; when you are finished
entering new text, press ESC.


The R command, like its lowercase counterpart, replaces text.
The difference is that it simply enters overstrike mode. The
characters you type replace what's on the screen, character by
character, until you type ESC. You can only overstrike a maximum
of one line; as you type RETURN, vi will open a new line, effectively
putting you into insert mode.

2.3.4 Changing Case
Changing the case of a letter is a special form of replacement.
The tilde (~) command will change a lowercase letter to uppercase,
or an uppercase letter to lowercase. Position the cursor on the letter
whose case you want to change, and type a ~. The case of the letter
will change, and the cursor will move to the next character.

In older versions of vi, you cannot specify a numeric prefix or text
object for the ~ to affect. Modern versions do allow a numeric
prefix.

If you want to change the case of more than one line at a time, you
must filter the text through a UNIX command like tr, as described
in Chapter 7.

2.3.5 Deleting Text
You can also delete any text in your file with the delete
command d. Like the change command, the delete command
requires a text object (the amount of text to be operated on). You
can delete by word (dw), by line (dd and D), or by other movement
commands that you will learn later.

With all deletions, you move to where you want the edit to take
place, then give the delete command (d) and the text object, such
as w for word.

2.3.5.1 Words
Suppose you have the following text in the file:
作者: projl    時(shí)間: 2008-06-11 13:22
with the cursor positioned as shown. You want to delete one are in
the first line.

Keystrokes Results
2w
Move the cursor to where you want the edit to begin (are).
dw
Give the delete word command (dw) to delete the word are.

dw deletes a word beginning where the cursor is positioned. Notice
that the space following the word is deleted.

dw can also be used to delete a portion of a word. In this example:


you want to delete the ed from the end of allowed.

Keystrokes

Results


dw
Give the delete word command (dw) to delete the word, beginning with
the position of the cursor.

dw always deletes the space before the next word on a line, but we
don't want to do that in the previous example. To retain the space
between words, use de, which will delete only to the end of a word.
Typing dE will delete to the end of a word, including punctuation.

You can also delete backward (db) or to the end or beginning of a
line (d$ or d0).

2.3.5.2 Lines
作者: projl    時(shí)間: 2008-06-11 13:23
The dd command deletes the entire line that the cursor is
on. dd will not delete part of a line. Like its complement cc, dd is a
special command. Using the same text as in the previous example,
with the cursor positioned on the first line as shown below:


you can delete the first two lines:

Keystrokes Results


2dd

Give the command to delete two lines (2dd). Note that even though the
cursor was not positioned on the beginning of the line, the entire line is
deleted.

If you are using a "dumb" terminal[2] (or a very slow one), line
deletions look different. The dumb terminal will not redraw the
screen until you scroll past the bottom of the screen. On a dumb
terminal the deletion looks like this:

[2] Dumb terminals are rather rare these days. Most of the time, you will run vi inside a terminal emulator on
a bitmapped screen.
Keystrokes Results

2dd


Give the command to delete two lines (2dd). An @ symbol "holds the
place" of the deleted line, until vi redraws the entire screen.


The D command deletes from the cursor position to the end of
the line. (D is a shortcut for d$.) For example, with the cursor
positioned as shown:


you can delete the portion of the line to the right of the cursor.

Keystrokes Results
作者: projl    時(shí)間: 2008-06-11 13:24
D
Give the command to delete the portion of the line to the right of the
cursor (D).
2.3.5.3 Characters
Often you want to delete only one or two characters. Just as r is
a special change command to replace a single character, x is a
special delete command to delete a single character. x deletes only
the character the cursor is on. In the line below:

zYou can move text by deleting text and then

[3]
you can delete the letter z by pressing x. A capital X deletes the
character before the cursor. Prefix either of these commands with a
number to delete that number of characters. For example, 5x will
delete the five characters under and to the right of the cursor.

[3] The mnemonic for x is that it is supposedly like "x-ing out" mistakes with a typewriter. Of course, who
uses a typewriter any more?
2.3.5.4 Problems with deletions

作者: projl    時(shí)間: 2008-06-11 13:36
This works only for a deleted line. Words, or a portion of a
line, are not saved in a buffer. If you want to restore a
deleted word or line fragment, and u won't work, use the pcommand by itself. This restores whatever you've last
deleted. The next few subsections will talk more about the
commands u and p.

2.3.6 Moving Text
In vi, you move text by deleting it and then placing that deleted
text elsewhere in the file, like a "cut and paste." Each time you
delete a text block, that deletion is temporarily saved in a special
buffer. Move to another position in your file and use the put
command (p) to place that text in the new position. You can move
any block of text, although moving is more useful with lines than
with words.


The put command (p) puts the text that is in the buffer after the
cursor position. The uppercase version of the command, P, puts the
text before the cursor. If you delete one or more lines, p puts the
deleted text on a new line(s) below the cursor. If you delete less
than an entire line, p puts the deleted text on the current line, after
the cursor.

Suppose in your file practice you have the text:


and want to move the second line, like a "cut and paste", below the
third line. Using delete, you can make this edit.

Keystrokes Results
dd
With the cursor on the second line, delete that line. The text is placed
in a buffer (reserved memory).
p
作者: projl    時(shí)間: 2008-06-11 13:37
Give the put command, p, to restore the deleted line at the next line
below the cursor. To finish reordering this sentence, you would also
have to change the capitalization and punctuation (with r) to match the
new structure.
Once you delete text, you must restore it before the
next change command or delete command. If you
make another edit that affects the buffer, your
deleted text will be lost. You can repeat the put
over and over, so long as you don't make a new
edit. In Chapter 4, you will learn how to save text
you delete in a named buffer so you can retrieve it
later.

2.3.6.1 Transposing two letters
You can use xp (delete character and put after cursor) to transpose
two letters. For example, in the word mvoe, the letters vo are
transposed (reversed). To correct a transposition, place the cursor
on v and press x, then p. By coincidence, the word transpose helps
you remember the sequence xp; x stands for trans, and p stands for
pose.

There is no command to transpose words. The section "More
Examples of Mapping Keys" in Chapter 7 discusses a short sequence
of commands that transposes two words.

2.3.7 Copying Text
Often you can save editing time (and keystrokes) by copying a
part of your file to use in other places. With the two commands y(for yank) and p (for put), you can copy any amount of text and put
that copied text in another place in the file. A yank command copies
the selected text into a special buffer, where it is held until another
yank (or deletion) occurs. You can then place this copy elsewhere in
the file with the put command.

As with change and delete, the yank command can be combined
with any movement command (yw, y$, 4yy). Yank is most
frequently used with a line (or more) of text, because to yank and
put a word usually takes longer than simply to insert the word.

The shortcut yy operates on an entire line, just as dd and cc do. But
the shortcut Y, for some reason, does not operate the way D and C
作者: projl    時(shí)間: 2008-06-11 13:37
do. Instead of yanking from the current position to the end of the
line, Y yanks the whole line. Y does the same thing as yy.

Suppose you have in your file practice the text:


You want to make three complete sentences, beginning each with
With a screen editor you can. Instead of moving through the file,
making this edit over and over, you can use a yank and put to copy
the text to be added.

Keystrokes Results
yy
Yank the line of text that you want to copy into the buffer. The cursor
can be anywhere on the line you want to yank (or on the first line of a
series of lines).
2j
Move the cursor to where you want to put the yanked text.
P
Put the yanked text above the cursor line with P.
jp
Move the cursor down a line and put the yanked text below the cursor
line with p.

Yanking uses the same buffer as deleting. Each new deletion or
yank replaces the previous contents of the yank buffer. As we'll see
in Chapter 4, up to nine previous yanks or deletions can be recalled
with put commands. You can also yank or delete directly into up to
作者: projl    時(shí)間: 2008-06-11 13:38
26 named buffers, which allows you to juggle multiple text blocks at
once.

2.3.8 Repeating or Undoing Your Last Command
Each edit command that you give is stored in a temporary buffer
until you give the next command. For example, if you insert the
after a word in your file, the command used to insert the text, along
with the text that you entered, is temporarily saved.

2.3.8.1 Repeat
Any time you make the same editing command over and over,
you can save time by duplicating it with the repeat command, the
period (.). Position the cursor where you want to repeat the editing
command, and type a period.

Suppose you have the following lines in your file:


You can delete one line, and then, to delete another line, simply
type a period.

Keystrokes Results
dd
Delete a line with the command dd.
.
Repeat the deletion.

Older versions of vi had problems repeating commands. For
example, such versions may have difficulty repeating a long
insertion when wrapmargin is set. If you have such a version, this
bug will probably bite you sooner or later. There's not a lot you can
do about it after the fact, but it helps to be forewarned. (Modern
versions do not seem to have this problem.) There are two ways
you can guard against a potential problem when repeating long
insertions. You can write your file (:w) before repeating the
作者: projl    時(shí)間: 2008-06-11 13:39
insertion (returning to this copy if the insertion doesn't work
correctly). You can also turn off wrapmargin like this:

:set wm=0

In Section 7.3.5, we'll show you an easy way to ause the
wrapmargin solution. In some versions of vi, the command CTRL-@
repeats the most recent insertion. CTRL-@ is typed in insert mode
and returns you to command mode.

2.3.8.2 Undo
As mentioned earlier, you can undo your last command if you
make an error. Simply press u. The cursor need not be on the line
where the original edit was made.

To continue the example above, showing deletion of lines in the file
practice:

Keystrokes

Results

u


u undoes the last command and restores the deleted line.

U, the uppercase version of u, undoes all edits on a single line, as
long as the cursor remains on that line. Once you move off a line,
you can no longer use U.

Note that you can undo your last undo with u, toggling between two
versions of text. u will also undo U, and U will undo any changes to a
line, including those made with u. (A tip: the fact that u can undo
itself leads to a nifty way to get around in a file. If you ever want to
get back to the site of your last edit, simply undo it. You will pop
back to the appropriate line. When you undo the undo, you'll stay
on that line.)

2.4 More Ways to Insert Text
You have inserted text before the cursor with the sequence:

itext to be insertedESC
作者: projl    時(shí)間: 2008-06-11 13:39
You've also inserted text after the cursor with the a command.
There are other insert commands for inserting text at different
positions relative to the cursor:

A

Append text to end of current line.

Insert text at beginning of line.

o

Open blank line below cursor for text.

O

Open blank line above cursor for text.

s

Delete character at cursor and substitute text.

S

Delete line and substitute text.

R

Overstrike existing characters with new characters.

All of these commands place you in insert mode. After inserting
text, remember to press ESC to escape back to command mode.

A (append) and I (insert) save you from having to move your
cursor to the end or beginning of the line before invoking insert
mode. (The A command saves one keystroke over $a. Although one
keystroke might not seem like much of a saving, the more adept鈥
作者: projl    時(shí)間: 2008-06-11 13:40
as cc. One of the best uses for s is to change one character to
several characters.

R ("large" replace) is useful when you want to start changing text,
but you don't know exactly how much. For example, instead of
guessing whether to say 3cw or 4cw, just type R and then enter your
replacement text.

2.4.1 Numeric Arguments for Insert Commands
Except for o and O, the above insert commands (plus i and a) take
numeric prefixes. With numeric prefixes, you might use the
commands i, I, a, and A to insert a row of underlines or alternating
characters. For example, typing 50i*ESC inserts 50 asterisks, and
typing 25a*- ESC appends 50 characters (25 pairs of asterisk and
hyphen). It's better to repeat only a small string of characters.[4]

[4] Very old versions of vi have difficulty repeating the insertion of more than one line's worth of text.
With a numeric prefix, r replaces that many characters with a
repeated instance of a single character. For example, in C or C++
code, to change || to &&, you would place the cursor on the first
pipe character, and type 2r&.

You can use a numeric prefix with S to substitute several lines. It's
quicker and more flexible, though, to use c with a movement
command.

A good case for using the s command with a numeric prefix is when
you want to change a few characters in the middle of a word.
Typing r wouldn't be correct, but typing cw would change too much
text. Using s with a numeric prefix is usually the same as typing R.

There are other combinations of commands that work naturally
together. For example, ea is useful for appending new text to the
end of a word. It helps to train yourself to recognize such frequent
combinations so that they become automatic.

2.5 Joining Two Lines with J
Sometimes while editing a file you will end up with a series of
short lines that are difficult to scan. When you want to merge two
lines into one, position the cursor anywhere on the first line, and
press J to join the two lines.

Suppose your file practice reads:
作者: projl    時(shí)間: 2008-06-11 13:40
Keystrokes Results
J
J joins the line the cursor is on with the line below.
.
Repeat the last command (J) with the . to join the next line with the
current line.
Using a numeric argument with J joins that number of consecutive
lines. In the example above, you could have joined three lines by
using the command 3J.

2.5.1 Problem Checklist

作者: projl    時(shí)間: 2008-06-11 13:41
Table 2.1. Edit Commands
Text Object Change Delete Copy
1 word cw dw yw
2 words, not counting punctuation 2cW or c2W 2dW or d2W 2yW or y2W
3 words back 3cb or c3b 3db or d3b 3yb or y3b
1 line cc dd yy or Y
To end of line c$ or C d$ or D y$
To beginning of line c0 d0 y0
Single character r x or X yl or yh
Five characters 5s 5x 5yl
Table 2.2. Movement
Movement Commands
, , , h, j, k, l
To first character of next line +
To first character of previous line -
To end of word e or E
Forward by word w or W
Backward by word b or B
To end of line $
To beginning of line 0
Table 2.3. Other Operations
Operations Commands
Place text from buffer P or p
Start vi, open file if specified vi file
Save edits, quit file ZZ
No saving of edits, quit file :q!
Table 2.4. Text Creation and Manipulation Commands
Editing Action Command
Insert text at current position i
Insert text at beginning of line I
Append text at current position a
Append text at beginning of line A
Open new line below cursor for new text o
Open new line above cursor for new text O
Delete line and substitute text S
Overstrike existing characters with new text R
Join current and next line J
Toggle case ~
Repeat last action .
Undo last change u
作者: projl    時(shí)間: 2008-06-11 13:41
Restore line to original state U
You can get by in vi using only the commands listed in these tables.
However, in order to harness the real power of vi (and increase
your own productivity), you will need more tools. The following
chapters describe those tools.
作者: projl    時(shí)間: 2008-06-11 13:42
Chapter 3. Moving Around in a Hurry

You will not use vi just to create new files. You'll spend a lot of your
time in vi editing existing files. You rarely want to simply open to
the first line in the file and move through it line by line. You want to
get to a specific place in a file and start work.

All edits begin by moving the cursor to where you want to begin the
edit (or, with ex line editor commands, by identifying the line
numbers to be edited). This chapter shows you how to think about
movement in a variety of ways (by screens, by text, by patterns, or
by line numbers). There are many ways to move in vi, since editing
speed depends on getting to your destination with only a few
keystrokes.

This chapter covers:


作者: projl    時(shí)間: 2008-06-11 13:43
3.1.1 Scrolling the Screen
There are vi commands to scroll forward and backward
through the file by full and half screens:

^F

Scroll forward one screen.

^B

Scroll backward one screen.

^D

Scroll forward half screen (down).

^U

Scroll backward half screen (up).

(In the list of commands above, the ^ symbol represents the CTRL
key. ^F means to hold down the CTRL key and press the f key
simultaneously.)

There are also commands to scroll the screen up one line (^E) and
down one line (^Y). However, these two commands do not send the
cursor to the beginning of the line. The cursor remains at the same
point in the line as when the command was issued.

3.1.2 Repositioning the Screen with z
If you want to scroll the screen up or down, but you want the
cursor to remain on the line where you left it, use the z command.

zRETURN Move current line to top of screen and scroll.
z. Move current line to center of screen and scroll.
z-Move current line to bottom of screen and scroll.

With the z command, using a numeric prefix as a multiplier makes
no sense. (After all, you would need to reposition the cursor to the
top of the screen only once. Repeating the same z command
wouldn't move anything.) Instead, z understands a numeric prefix
as a line number that it will use in place of the current line. For
作者: projl    時(shí)間: 2008-06-11 13:43
example, z RETURN moves the current line to the top of the screen,
but 200z RETURN moves line 200 to the top of the screen.

3.1.3 Redrawing the Screen
Sometimes while you're editing, messages from your
computer system will display on your screen. These messages don't
become part of your editing buffer, but they do interfere with your
work. When system messages appear on your screen, you need to
redisplay, or redraw, the screen.

Whenever you scroll, you redraw part of (or all of) the screen, so
you can always get rid of unwanted messages by scrolling them off
the screen and then returning to your previous position. But you
can also redraw the screen without scrolling, by typing CTRL-L.

3.1.4 Movement Within a Screen
You can also keep your current screen, or view of the file, and
move around within the screen using:

H

Move to home鈥攖op line on screen.

M

Move to middle line on screen.

Move to last line on screen.

nH

Move to n lines below top line.

nL

Move to n lines above last line.

H moves the cursor from anywhere on the screen to the first, or
"home," line. M moves to the middle line, L to the last. To move to
the line below the first line, use 2H.

Keystrokes Results
作者: projl    時(shí)間: 2008-06-11 13:44
L
Move to the last line of the screen with the L command.
2H
Move to the second line of the screen with the 2H command. (H alone
moves to the top line of the screen.)
3.1.5 Movement by Line
Within the current screen there are also commands to
move by line. You've already seen j and k. You can also use:

RETURN Move to first character of next line.
+ Move to first character of next line.
-Move to first character of previous line.

The above three commands move down or up to the first character
of the line, ignoring any spaces or tabs. j and k, by contrast, move
the cursor down or up to the first position of a line, even if that
position is blank (and assuming that the cursor started at the first
position).

3.1.5.1 Movement on the current line
Don't forget that h and l move the cursor to the left and right and
that 0 and $ move the cursor to the beginning or end of the line.
You can also use:

^

Move to first non-blank character of current line.

n|

Move to column n of current line.
作者: projl    時(shí)間: 2008-06-11 13:44
As with the line movement commands above, ^ moves to the first
character of the line, ignoring any spaces or tabs. 0, by contrast,
moves to the first position of the line, even if that position is blank.

3.2 Movement by Text Blocks
Another way that you can think of moving through a vi file is by
text blocks鈥攚ords, sentences, paragraphs, or sections.

You have already learned to move forward and backward by word
(w, W, b or B). In addition, you can use these commands:

e

Move to end of word.

E

Move to end of word (ignore punctuation).

(

Move to beginning of current sentence.

)

Move to beginning of next sentence.

{

Move to beginning of current paragraph.

}

Move to beginning of next paragraph.

[[

Move to beginning of current section.

]]

Move to beginning of next section.

To find the end of a sentence, vi looks for one of the punctuation
marks ?.!. vi locates the end of a sentence when the punctuation
is followed by at least two spaces or when it appears as the last
作者: projl    時(shí)間: 2008-06-11 13:45
non-blank character on a line. If you have left only a single space
following a period, or if the sentence ends with a quotation mark, vi
won't recognize the sentence.

A paragraph is defined as text up to the next blank line, or up to
one of the default paragraph macros (.IP, .PP, .LP, or .QP) from the
troff MS macro package. Similarly, a section is defined as text up to
the next default section macro (.NH, .SH, .H 1, .HU). The macros
that are recognized as paragraph or section separators can be
customized with the :set command, as described in Chapter 7.

Remember that you can combine numbers with movement. For
example, 3) moves ahead three sentences. Also remember that you
can edit using movement commands: d) deletes to the end of the
current sentence, 2y} copies (yanks) two paragraphs ahead.

3.3 Movement by Searches
One of the most useful ways to move around in a large file
quickly is by searching for text, or more properly, a pattern of
characters. Sometimes a search can be performed to find a
misspelled word or to find each occurrence of a variable in a
program.

The search command is the special character / (slash). When you
enter a slash, it appears on the bottom line of the screen; you then
type in the pattern that you want to find: /pattern.

A pattern can be a whole word or any other sequence of characters
(called a "character string"). For example, if you search for the
characters red, you will match red as a whole word, but you'll also
match occurred. If you include a space before or after pattern, the
spaces will be treated as part of the word. As with all bottom-line
commands, press RETURN to finish. vi, like all other UNIX editors,
has a special pattern-matching language that allows you to look for
variable text patterns; for example, any word beginning with a
capital letter, or the word The at the beginning of a line.

We'll talk about this more powerful pattern-matching syntax in
Chapter 6. For right now, think of pattern simply as a word or
phrase.

vi begins the search at the cursor and searches forward, wrapping
around to the start of the file if necessary. The cursor will move to
the first occurrence of the pattern. If there is no match, the
message "Pattern not found" will be shown on the status line.[1]
作者: projl    時(shí)間: 2008-06-11 13:46
[1] The exact messages will vary with different vi clones, but their meanings will be the same. In general, we
won't bother noting everywhere that the text of a message may be different; in all cases the information
conveyed will be the same.
Using the file practice, here's how to move the cursor by searches:

Keystrokes Results
/edits
Search for the pattern edits. Press RETURN to enter. The cursor moves
directly to that pattern.
/scr
Search for the pattern scr. Press RETURN to enter. Note that there is no
space after scr.

The search wraps around to the front of the file. Note that you can
give any combination of characters; a search does not have to be
for a complete word.

To search backward, type a ? instead of a /:

?pattern

In both cases, the search wraps around to the beginning or end of
the file, if necessary.

3.3.1 Repeating Searches
The last pattern that you searched for stays available
throughout your editing session. After a search, instead of repeating
your original keystrokes, you can use a command to search again
for the last pattern.

n Repeat search in same direction.
N Repeat search in opposite direction.
/ RETURN Repeat search forward.
?RETURN Repeat search backward.

Since the last pattern stays available, you can search for a pattern,
do some work, and then search again for the same pattern without
retyping it by using n, N, / or ?. The direction of your search (/ is
作者: projl    時(shí)間: 2008-06-11 13:46
forward, ? is backward) is displayed at the bottom left of the
screen.[2]

[2] nvi 1.79 does not show the direction for the n and N commands. vim 5.x puts the search text into the
command line too.
To continue with the example above, since the pattern scr is still
available for search, you can:

Keystrokes Results
n
Move to the next instance of the pattern scr (from screen to scroll) with
the n (next) command.
?you
Search backward with ? from the cursor to the first occurrence of you.
You need to press RETURN after typing the pattern.
N
Repeat previous search for you but in the opposite direction (forward).

Sometimes you want to find a word only if it is further ahead; you
don't want the search to wrap around earlier in the file. vi has an
option, wrapscan, that controls whether searches wrap. You can
disable wrapping like this:

:set nowrapscan

When nowrapscan is set and a forward search fails, the status line
displays the message:

Address search hit BOTTOM without matching pattern

When nowrapscan is set and a backward search fails, the message
displays "TOP" instead of "BOTTOM".

This section has given only the barest introduction to searching for
patterns. Chapter 6 will teach you more about pattern matching and
its use in making global changes to a file.
作者: projl    時(shí)間: 2008-06-11 13:47
3.3.1.1 Changing through searching
You can combine the / and ? search operators with the commands
that change text, such as c and d. Continuing with the previous
example:

Keystrokes

Results

d?move


Delete from before the cursor up to and through the word move.

Note how the deletion occurs on a character basis, whole lines are
not deleted.

3.3.2 Current Line Searches
There are also miniature versions of the search commands that
operate within the current line. The command fx moves the cursor
to the next instance of the character x (where x stands for any
character). The command tx moves the cursor to the character
before the next instance of x. Semicolons can then be used
repeatedly to "find" your way along.

The in-line search commands are summarized below. None of these
commands will move the cursor to the next line.

fx Find (move cursor to) next occurrence of x in the line, where x stands for any
character.
Fx Find (move cursor to) previous occurrence of x in the line.
tx Find (move cursor to) character before next occurrence of x in the line.
Tx Find (move cursor to) character after previous occurrence of x in the line.
; Repeat previous find command in same direction.
, Repeat previous find command in opposite direction.

With any of these commands, a numeric prefix n will locate the nth
occurrence. Suppose you are editing in practice, on this line:


Keystrokes Results
fo
Find the first occurrence of o in your current line with f.
;
作者: projl    時(shí)間: 2008-06-11 13:47
Move to the next occurrence of o with the ; command (find next o).
dfx deletes up to and including the named character x. This
command is useful in deleting or yanking partial lines. You might
need to use dfx instead of dw if there were symbols or punctuation
within the line that made counting words difficult. The t command
works just like f, except that it positions the cursor before the
character searched for. For example, the command ct. could be
used to change text up to the end of a sentence, leaving the period.

3.4 Movement by Line Number
Lines in a file are numbered sequentially, and you can move
through a file by specifying line numbers.

Line numbers are useful for identifying the beginning and end of
large blocks of text you want to edit. Line numbers are also useful
for programmers, since compiler error messages refer to line
numbers. Line numbers are also used by ex commands, which you
will learn in the next chapters.

If you are going to move by line numbers, you must have a way to
identify them. Line numbers can be displayed on the screen using
the :setnu option described in Chapter 7. In vi, you can also
display the current line number on the bottom of the screen.

The command CTRL-G causes the following to be displayed at the
bottom of your screen: the current line number, the total number of
lines in the file, and what percentage of the total the present line
number represents. For example, for the file practice, CTRL-G might
display:

"practice" line 3 of 6 --50%--

CTRL-G is useful either for displaying the line number to use in a
command or for orienting yourself if you have been distracted from
your editing session.

Depending upon the implementation of vi you're using, you may see
additional information, such as what column the cursor is on, and
an indication as to whether or not the file has been modified but not
yet written out. The exact format of the message will vary as well.
作者: projl    時(shí)間: 2008-06-11 13:48
3.4.1 The G (Go To) Command
You can use line numbers to move the cursor through a file. The
G (go to) command uses a line number as a numeric argument and
moves directly to that line. For instance, 44G moves the cursor to
the beginning of line 44. G without a line number moves the cursor
to the last line of the file.

Typing two backquotes (` `) returns you to your original position
(the position where you issued the last G command), unless you
have done some edits in the meantime. If you have made an edit,
and then moved the cursor using some command other than G, ` `
will return the cursor to the site of your last edit. If you have issued
a search command (/ or ?), ` ` will return the cursor to its position
when you started the search. A pair of apostrophes (' ') works
much like two backquotes, except that it returns the cursor to the
beginning of the line instead of the exact position on that line where
your cursor had been.

The total number of lines shown with CTRL-G can be used to give
yourself a rough idea of how many lines to move. If you are on line
10 of a 1,000 line file:

"practice" line 10 of 1000 --1%--

and know that you want to begin editing near the end of that file,
you could give an approximation of your destination with 800G.

Movement by line number is a tool that can move you quickly from
place to place through a large file.

3.5 Review of vi Motion Commands
Table 3.1 summarizes the commands covered in this chapter.

Table 3.1. Movement Commands
Movement Command
Scroll forward one screen. ^F
Scroll backward one screen. ^B
Scroll forward half screen. ^D
Scroll backward half screen. ^U
Scroll forward one line. ^E
Scroll backward one line. ^Y
Move current line to top of screen and scroll. z RETURN
Move current line to center of screen and scroll. z.
作者: projl    時(shí)間: 2008-06-11 13:49
Move current line to bottom of screen and scroll. z-
Redraw the screen. ^L
Move to home鈥攖op line of screen. H
Move to middle line of screen. M
Move to bottom line of screen. L
Move to first character of next line. RETURN
Move to first character of next line. +
Move to first character of previous line. -
Move to first non-blank character of current line. ^
Move to column n of current line. n|
Move to end of word. e
Move to end of word (ignore punctuation). E
Move to beginning of current sentence. (
Move to beginning of next sentence. )
Move to beginning of current paragraph. {
Move to beginning of next paragraph. }
Move to beginning of current section. [[
Move to beginning of next section. ]]
Search forward for pattern. /pattern
Search backward for pattern. ?pattern
Repeat last search. n
Repeat last search in opposite direction. N
Repeat last search forward. /
Repeat last search backward. ?
Move to next occurrence of x in current line. fx
Move to previous occurrence of x in current line. Fx
Move to just before next occurrence of x in current line. tx
Move to just after previous occurrence of x in current line. Tx
Repeat previous find command in same direction. ;
Repeat previous find command in opposite direction. ,
Go to given line n. nG
Go to end of file. G
Return to previous mark or context. ` `
Return to beginning of line containing previous mark. ' '
Show current line (not a movement command). ^G
作者: projl    時(shí)間: 2008-06-11 13:49
Chapter 4. Beyond the Basics

You have already been introduced to the basic vi editing commands,
i, a, c, d, and y. This chapter expands on what you already know
about editing. It covers:


作者: projl    時(shí)間: 2008-06-11 13:50
4.2 Options When Starting vi
In this handbook, you have invoked the vi editor with the
command:

$ vi file

There are other options to the vi command that can be helpful. You
can open a file directly to a specific line number or pattern. You can
also open a file in read-only mode. Another option recovers all
changes to a file that you were editing when the system crashed.

4.2.1 Advancing to a Specific Place
When you begin editing an existing file, you can call the file in and
then move to the first occurrence of a pattern or to a specific line
number. You can also specify your first movement by search or by
line number right on the command line:[1]

[1] According to the POSIX standard, vi should use -c command instead of +command as shown here. Typically,
for backwards compatibility, both versions are accepted.
$

vi +

n file

Opens file at line number n.

$

vi +

file

Opens file at last line.

$

vi +/

pattern file

Opens file at the first occurrence of pattern.

In the file practice, to open the file and advance directly to the line
containing the word Screen, enter:

Keystrokes Results
作者: projl    時(shí)間: 2008-06-11 13:50
vi +/Screen practice
Give the vi command with the option +/pattern to go
directly to the line containing Screen.
As you see in the example above, your search pattern will not
necessarily be positioned at the top of the screen. If you include
spaces in the pattern, you must enclose the whole pattern within
single or double quotes:[2]

[2] It is the shell that imposes the quoting requirement, not vi.
+/"you make"

or escape the space with a backslash:

+/you\ make

In addition, if you want to use the general pattern-matching syntax
described in Chapter 6, you may need to protect one or more
special characters from interpretation by the shell with either single
quotes or backslashes.

Using +/pattern is helpful if you have to leave an editing session in
the middle. You can mark your place by inserting a pattern such as
ZZZ or HERE. Then when you return to the file, all you have to
remember is /ZZZ or /HERE.

Normally, when you're editing in vi, the wrapscanoption is enabled. If you've customized your
environment so that wrapscan is always disabled
(see Section 3.3.1), you might not be able to use
+/pattern. If you try to open a file this way, vi
opens the file at the last line and displays the
message "Address search hit BOTTOM without
matching pattern."

4.2.2 Read-only Mode
There will be times when you want to look at a file but want to
protect that file from inadvertent keystrokes and changes. (You
作者: projl    時(shí)間: 2008-06-11 13:51
might want to call in a lengthy file to practice vi movements, or you
might want to scroll through a command file or program). You can
enter a file in read-only mode and use all the vi movement
commands, but you won't be able to change the file.

To look at a file in read-only mode, enter either:

$ vi -R file

or:

$ view file

(The view command, like the vi command, can use any of the
command-line options for advancing to a specific place in the file.)[3]
If you do decide to make some edits to the file, you can override
read-only mode by adding an exclamation point to the write
command:

[3] Typically view is just a link to vi.
:w!

or:

:wq!

If you have a problem writing out the file, see the problem
checklists summarized in Appendix D.

4.2.3 Recovering a Buffer
Occasionally there is a system failure while you are editing a file.
Ordinarily, any edits made after your last write (save) are lost.
However, there is an option, -r, which lets you recover the edited
buffer at the time of a system crash.

When you first log on after the system is running again, you will
receive a mail message stating that your buffer has been saved. In
addition, if you type the command:

$ ex -r

or:

$ vi -r

you will get a list of any files that the system has saved.
作者: projl    時(shí)間: 2008-06-11 13:51
Use the -r option with a file name to recover the edited buffer. For
example, to recover the edited buffer of the file practice after a
system crash, enter:

$ vi -r practice

It is wise to recover the file immediately, lest you inadvertently
make edits to the file, and then have to resolve a version skew
between the preserved buffer and the newly edited file.

You can force the system to preserve your buffer even when there
is not a crash by using the command :pre. You may find it useful if
you have made edits to a file, then discover that you can't save
your edits because you don't have write permission. (You could also
just write out a copy of the file under another name or into a
directory where you do have write permission. See Section 1.2.1.)


Recovery for the various clones may work
differently, and can change from version to version.
It is best to check your local documentation. vile
does not support any kind of recovery. The vile
documentation recommends the use of the
autowrite and autosave options. How to do this is
described in Section 7.1.

4.3 Making Use of Buffers
You have seen that while you are editing, your last deletion (d or x)
or yank (y) is saved in a buffer (a place in stored memory). You can
access the contents of that buffer and put the saved text back in
your file with the put command (p or P).

The last nine deletions are stored by vi in numbered buffers. You
can access any of these numbered buffers to restore any (or all) of
the last nine deletions. (Small deletions, of only parts of lines, are
not saved in numbered buffers, however. These deletions can only
be recovered by using the p or P command immediately after you've
made the deletion.)

vi also allows you to place yanks (copied text) in buffers identified
by letters. You can fill up to 26 (a-z) buffers with yanked text and
restore that text with a put command at any time in your editing
session.
作者: projl    時(shí)間: 2008-06-11 13:52
4.3.1 Recovering Deletions
Being able to delete large blocks of text at a single bound is all very
well and good, but what if you mistakenly delete 53 lines that you
need? There is a way to recover any of your past nine deletions, for
they are saved in numbered buffers. The last delete is saved in
buffer 1, the second-to-last in buffer 2, and so on.

To recover a deletion, type " (double quote), identify the buffered
text by number, then give the put command. To recover your
second-to-last deletion from buffer 2:

"2p

The deletion in buffer 2 is placed after the cursor.

If you're not sure which buffer contains the deletion you want to
restore, you don't have to keep typing "np over and over again. If
you use the repeat command (.) with p after u, it automatically
increments the buffer number. As a result, you can search through
the numbered buffers as follows:

"1pu.u.u

etc.

to put the contents of each succeeding buffer in the file one after
the other. Each time you type u, the restored text is removed; when
you type a dot (.), the contents of the next buffer is restored to
your file. Keep typing u and . until you've recovered the text you're
looking for.

4.3.2 Yanking to Named Buffers
You have seen that you must put (p or P) the contents of the
unnamed buffer before you make any other edit, or the buffer will
be overwritten. You can also use y and d with a set of 26 named
buffers (a-z) which are specifically available for copying and moving
text. If you name a buffer to store the yanked text, you can retrieve
the contents of the named buffer at any time during your editing
session.

To yank into a named buffer, precede the yank command with a
double quote (") and the character for the name of the buffer you
want to load. For example:

"dyy

Yank current line into buffer d.
作者: projl    時(shí)間: 2008-06-11 13:53
"a7yy

Yank next seven lines into buffer a.

After loading the named buffers and moving to the new position,
use p or P to put the text back:

"dP

Put the contents of buffer d before cursor.

"ap

Put the contents of buffer a after cursor.

There is no way to put part of a buffer into the text鈥攊t is all or
nothing.

In the next chapter, you'll learn to edit multiple files. Once you
know how to travel between files without leaving vi, you can use
named buffers to selectively transfer text between files.

You can also delete text into named buffers using much the same
procedure:

"a5dd

Delete five lines into buffer a.

If you specify a buffer name with a capital letter, your yanked or
deleted text will be appended to the current contents of that buffer.
This allows you to be selective in what you move or copy. For
example:

"zd)

Delete from cursor to end of current sentence and save in
buffer z.

2)

Move two sentences further on.

"Zy)

Add the next sentence to buffer z. You can continue adding
more text to a named buffer for as long as you like鈥攂ut be
warned: if you once forget, and yank or delete to the buffer
without specifying its name in capitalized form, you'll
overwrite the buffer, losing whatever you had accumulated in
it.
作者: projl    時(shí)間: 2008-06-11 13:53
4.4 Marking Your Place
During a vi session, you can mark your place in the file with an
invisible "bookmark," perform edits elsewhere, then return to your
marked place. In command mode:

m x

Marks the current position with x (x can be any letter).

' x

(apostrophe) Moves the cursor to the first character of the
line marked by x.

` x

(backquote) Moves the cursor to the character marked by x.

``

(backquotes) Returns to the exact position of the previous
mark or context after a move.

''

(apostrophes) Returns to the beginning of the line of the
previous mark or context.

Place markers are set only during the current vi
session; they are not stored in the file.
4.5 Other Advanced Edits
There are other advanced edits that you can execute with vi, but to
use them you must first learn a bit more about the ex editor by
reading the next chapter.

4.6 Review of vi Buffer and Marking Commands
Table 4.2 summarizes the command-line options common to all
versions of vi. Table 4.3 and Table 4.4 summarize the buffer and
marking commands.
作者: projl    時(shí)間: 2008-06-11 13:54
Table 4.2. Command-Line Options
Option Meaning
+n file Open file at line number n.
+file Open file at last line.
+/pattern
file Open file at first occurrence of pattern.
-c command
file
Run command after opening file; usually a line number or search
(POSIX version of +).
-R Operate in read-only mode (same as using view instead of vi).
-r Recover files after a crash.
Table 4.3. Buffer Names
Buffer
Names Buffer Use
1-9 The last nine deletions, from most to least recent.
a-z
Named buffers for you to use as needed. Uppercase letters append to
the buffer.
Table 4.4. Buffer and Marking Commands
Command Meaning
"bcommand Do command with buffer b.
mx Mark current position with x.
'x Move cursor to first character of line marked by x.
`x Move cursor to character marked by x.
`` Return to exact position of previous mark or context.
'' Return to beginning of the line of previous mark or context.
作者: projl    時(shí)間: 2008-06-11 13:54
Chapter 5. Introducing the ex Editor

If this is a handbook on vi, why would we include a chapter on
another editor? ex is not really another editor. vi is the visual mode
of the more general, underlying line editor, ex. Some ex commands
can be useful to you while you are working in vi, since they can
save you a lot of editing time. Most of these commands can be used

[1]
without ever leaving vi.

[1] vile is different from the other clones. Many of the more advanced ex commands simply don't work.
Instead of noting each one, more details are provided in Chapter 12.
You already know how to think of files as a sequence of numbered
lines. ex gives you editing commands with greater mobility and
scope. With ex you can move easily between files and transfer text
from one file to another in a variety of ways. You can quickly edit
blocks of text larger than a single screen. And with global
replacement you can make substitutions throughout a file for a
given pattern.

This chapter introduces ex and its commands. You will learn how to:


作者: projl    時(shí)間: 2008-06-11 13:55
Many of the commands we'll see in this chapter
have filename arguments. Although it's possible, it
is usually a very bad idea to have spaces in your
files' names. ex will be confused to no end, and you
will go to more trouble than it's worth trying to get
the filenames to be accepted. Use underscores,
dashes, or periods to separate the components of
your file names, and you'll be much happier.

Before you start off simply memorizing ex commands (or worse,
ignoring them), let's first take some of the mystery out of line
editors. Seeing how ex works when it is invoked directly will help
make sense of the sometimes obscure command syntax.

Open a file that is familiar to you and try a few ex commands. Just
as you can invoke the vi editor on a file, you can invoke the ex line
editor on a file. If you invoke ex, you will see a message about the
total number of lines in the file, and a colon command prompt.

For example:

$ ex practice"practice" 6 lines, 320 characters:

You won't see any lines in the file unless you give an ex command
that causes one or more lines to be displayed.

ex commands consist of a line address (which can simply be a line
number) plus a command; they are finished with a carriage return.
One of the most basic commands is p for print (to the screen). So,
for example, if you type 1p at the prompt, you will see the first line
of the file:

:1p

With a screen editor you can

:

In fact, you can leave off the p, because a line number by itself is
equivalent to a print command for that line. To print more than one
line, you can specify a range of line numbers (for example, 1,3鈥
作者: projl    時(shí)間: 2008-06-11 13:55
scroll the page, move the cursor,

delete lines, insert characters, and more,

A command without a line number is assumed to affect the current
line. So, for example, the substitute command (s), which allows you
to substitute one word for another, could be entered like this:

:1

With a screen editor you can

:s/screen/line/

With a line editor you can

Notice that the changed line is reprinted after the command is
issued. You could also make the same change like this:

:1s/screen/line/
With a line editor you can

Even though you will be invoking ex commands from vi and will not
be using them directly, it is worthwhile to spend a few minutes in ex
itself. You will get a feel for how you need to tell the editor which
line (or lines) to work on, as well as which command to execute.

After you have given a few ex commands on your practice file, you
should invoke vi on that same file, so that you can see it in the
more familiar visual mode. The command :vi will get you from ex
to vi.

To invoke an ex command from vi, you must type the special
bottom line character : (colon). Then type the command and press
RETURN to execute it. So, for example, in the ex editor you move to
a line simply by typing the number of the line at the colon prompt.
To move to line 6 of a file using this command from within vi, enter:

:6

Press RETURN.

Following the exercise, we will discuss ex commands only as they
are executed from vi.

5.1.1 Exercise: The ex Editor
At the UNIX prompt, invoke ex editor on a file
called practice: ex practice
A message appears: "practice" 6 lines, 320characters
Go to and print (display) first line: :1
Print (display) lines 1 through 3: :1,3
作者: projl    時(shí)間: 2008-06-11 13:56
Substitute screen for line on line 1: :1s/screen/line
Invoke vi editor on file: :vi
Go to first line: :1

5.1.2 Problem Checklist

作者: projl    時(shí)間: 2008-06-11 13:57

作者: projl    時(shí)間: 2008-06-11 13:57
:1,10#

would display the line numbers from line one to line ten.

As described in Chapter 3, you can also use the CTRL-G command
to display the current line number. You can thus identify the line
numbers corresponding to the start and end of a block of text by
moving to the start of the block, typing CTRL-G, then moving to the
end of the block and typing CTRL-G again.

Yet another way to identify line numbers is with the ex = command:

:=

Print the total number of lines.

:.=

Print the line number of the current line.

:/ pattern/=

Print the line number of the first line that matches pattern.

5.2.3 Line Addressing Symbols
You can also use symbols for line addresses. A dot (.) stands for
the current line; $ stands for the last line of the file. % stands for
every line in the file; it's the same as the combination 1,$. These
symbols can also be combined with absolute line addresses. For
example:

:.,$d

Delete from current line to end of file.

:20,.m$

Move from line 20 through the current line to the end of the
file.

:%d

Delete all the lines in a file.

:%t$
作者: projl    時(shí)間: 2008-06-11 13:58
Copy all lines and place them at the end of the file (making a
consecutive duplicate).

In addition to an absolute line address, you can specify an address
relative to the current line. The symbols + and -work like
arithmetic operators. When placed before a number, these symbols
add or subtract the value that follows. For example:

:.,.+20d

Delete from current line through the next 20 lines.

:226,$m.-2

Move lines 226 through the end of the file to two lines above
the current line.

:.,+20#

Display line numbers from the current line to 20 lines further
on in the file.

In fact, you don't need to type the dot (.) when you use + or -,
because the current line is the assumed starting position.

Without a number following them, + and -are equivalent to +1 and
-1, respectively.[2] Similarly, ++ and --each extend the range by an
additional line, and so on. The + and - can also be used with search
patterns, as shown in the next section.

[2] In a relative address, you shouldn't separate the plus or minus symbol from the number that follows it.
For example, +10 means "10 lines following," but +10 means "11 lines following (1+10)," which is probably
not what you mean (or want).
The number 0 stands for the top of the file (imaginary line 0). 0 is
equivalent to 1-, and both allow you to move or copy lines to the
very start of a file, before the first line of existing text. For example:

:-,+t0

Copy three lines (the line above the cursor through the line
below the cursor) and put them at the top of the file.

5.2.4 Search Patterns
Another way that ex can address lines is by using search patterns.
For example:
作者: projl    時(shí)間: 2008-06-11 13:58
:/ pattern/d

Delete the next line containing pattern.

: /pattern/+d

Delete the line below the next line containing pattern. (You
could also use +1 instead of + alone.)

: /pattern1/,/ pattern2/d

Delete from the first line containing pattern1 through the first
line containing pattern2.

:.,/ pattern/m23

Take the text from the current line (.) through the first line
containing pattern and put it after line 23.

Note that patterns are delimited by a slash both before and after.

If you make deletions by pattern with vi and ex, there is a
difference in the way the two editors operate. Suppose your file
practice contains the lines:


Keystrokes Results
d/while
The vi delete to pattern command deletes from the cursor up to the
word while, but leaves the remainder of both lines.
:.,/while/d
The ex command deletes the entire range of addressed lines; in this
case both the current line and the line containing the pattern. All
lines are deleted in their entirety.

5.2.5 Redefining the Current Line Position
Sometimes, using a relative line address in a command can give
you unexpected results. For example, suppose the cursor is on line
作者: projl    時(shí)間: 2008-06-11 13:59
1, and you want to print line 100 plus the five lines below it. If you
type:

:100,+5 p

you'll get an error message saying, "First address exceeds second."
The reason the command fails is that the second address is
calculated relative to the current cursor position (line 1), so your
command is really saying this:

:100,6 p

What you need is some way to tell the command to think of line 100
as the "current line," even though the cursor is on line 1.

ex provides such a way. When you use a semicolon instead of a
comma, the first line address is recalculated as the current line. For
example, the command:

:100;+5 p

prints the desired lines. The +5 is now calculated relative to line

100. A semicolon is useful with search patterns as well as absolute
addresses. For example, to print the next line containing pattern,
plus the 10 lines that follow it, enter the command:
:/pattern/;+10 p

5.2.6 Global Searches
You already know how to use / (slash) in vi to search for patterns of
characters in your files. ex has a global command, g, that lets you
search for a pattern and display all lines containing the pattern
when it finds them. The command :g! does the opposite of :g. Use
:g! (or its synonym :v) to search for all lines that do not contain
pattern.

You can use the global command on all lines in the file, or you can
use line addresses to limit a global search to specified lines or to a
range of lines.

:g/ pattern

Finds (moves to) the last occurrence of pattern in the file.

:g/ pattern/p

Finds and displays all lines in the file containing pattern.
作者: projl    時(shí)間: 2008-06-11 14:00
:g!/ pattern/nu

Finds and displays all lines in the file that don't contain
pattern; also displays the line number for each line found.

:60,124g/ pattern/p

Finds and displays any lines between lines 60 and 124
containing pattern.

As you might expect, g can also be used for global replacements.
We'll talk about that in Chapter 6.

5.2.7 Combining ex Commands
You don't always need to type a colon to begin a new ex command.
In ex, the vertical bar (|) is a command separator, allowing you to
combine multiple commands from the same ex prompt (in much the
same way that a semicolon separates multiple commands at the
UNIX shell prompt). When you use the |, keep track of the line
addresses you specify. If one command affects the order of lines in
the file, the next command does its work using the new line
positions. For example:

:1,3d | s/thier/their/

Delete lines 1 through 3 (leaving you now on the top line of
the file); then make a substitution on the current line (which
was line 4 before you invoked the ex prompt).

:1,5 m 10 | g/pattern/nu

Move lines 1 through 5 after line 10, and then display all lines
(with numbers) containing pattern.

Note the use of spaces to make the commands easier to read.

5.3 Saving and Exiting Files
You 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.

:w
作者: projl    時(shí)間: 2008-06-11 14:00
Writes (saves) the buffer to the file but does not exit. You can
(and should) use :w throughout your editing session to
protect your edits against system failure or a major editing
error.

:q

Quits the editor (and returns to the UNIX prompt).

:wq

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 (exits) the editor. The file is
written only if it has been modified.[3]

[3] The difference between :wq and is important when editing source code and using make, which
performs actions based upon file modification times.
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.
作者: projl    時(shí)間: 2008-06-11 14:31
5.3.1 Renaming the Buffer
You 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 File
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, 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:

:230,$w newfile

Saves from line 230 to end of file in newfile.

:.,600w newfile

Saves from the current line to line 600 in newfile.

5.3.3 Appending to a Saved File
You 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
作者: projl    時(shí)間: 2008-06-11 14:32
newfile would contain lines 1-10 and from line 340 to the end of the
buffer.

5.4 Copying a File into Another File
Sometimes you want to copy text or data already entered on the
system into the file you are editing. In vi you can read in the
contents of another file with the ex command:

:read filename

or its abbreviation:

:r filename

This command inserts the contents of filename starting on the line
after the cursor position in the file. If you want to specify a line
other than the one the cursor's on, simply type the line number (or
other line address) you want before the read or r command.

Let's suppose you are editing the file practice and want to read in a
file called data from another directory called /home/tim. Position
the cursor one line above the line where you want the new data
inserted, and enter:

:r /home/tim/data

The entire contents of /home/tim/data are read into practice,
beginning below the line with the cursor.

To read in the same file and place it after line 185, you would enter:

:185r /home/tim/data

Here are other ways to read in a file:

r /home/tim/data

Place the read-in file at the end of the current file.

:0r /home/tim/data

Place the read-in file at the very beginning of the current file.

:/ pattern/r /home/tim/data

Place the read-in file in the current file, after the line
containing pattern.
作者: projl    時(shí)間: 2008-06-11 14:33
5.5 Editing Multiple Files
ex commands enable you to switch between multiple files. The
advantage to editing multiple files is speed. If you are sharing the
system with other users, it takes time to exit and reenter 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
(see Chapter 7), and you keep yank buffers so that you can copy
text from one file to another.

5.5.1 Invoking vi on Multiple Files
When you first invoke vi, you can name more than one file to edit,
and then use ex commands to travel between the files. For
example:

$ vi file1 file2

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).

Suppose you want to edit two files, practice and note.

Keystrokes Results
vi
practicenote
Open the two files practice and note. The first-named file, practice,
appears on your screen. Perform any edits.
:w
Save the edited file practice with the ex command w. Press RETURN.
:n
Call in the next file, note, with the ex command n. Press RETURN.
Perform any edits.

Save the second file, note, and quit the editing session.
作者: projl    時(shí)間: 2008-06-11 14:33
5.5.2 Using the Argument List
ex actually lets you do more than just move to the next file in the
argument list with :n. The :args command (abbreviated :ar) lists
the files named on the command line, with the current file enclosed
in brackets.

Keystrokes Results
vi practicenote
Open the two files practice and note. The first-named file, practice,
appears on your screen.
:args
vi displays the argument list in the status line, with brackets
around the current filename.

The :rewind (:rew) command resets the current file to be the first
file named on the command line. elvis and vim provide a
corresponding :last command to move to the last file on the
command line.

5.5.3 Calling in New Files
You don't have to call in multiple files at the beginning of your
editing session. You can switch to another file at any time with the
ex command :e. If you want to edit another file within vi, you first
need to save your current file (:w), then give the command:

:e filename

Suppose you are editing the file practice and want to edit the file
letter, then return to practice.

Keystrokes Results
:w Save practice with w and press RETURN. practice is saved and remains
on the screen. You can now switch to another file, because your edits
are saved.
:e
letter
Call in the file letter with e and press RETURN. Perform any edits.
作者: projl    時(shí)間: 2008-06-11 14:34
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 easily back and forth between two files.
In the example given just above, you could return to the first file,
practice, by typing the command :e #. You could also read the file
practice into the current file by typing :r #.

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.

For example, if after making some edits to letter, you wanted to
discard the edits and return to practice, you could type :e! #.

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

:e!

In contrast to the # symbol, % is useful mainly when writing out the
contents of the current buffer to a new file. For example, a few
pages earlier, in the section "Renaming the Buffer," we showed how
to save a second version of the file practice with the command:

:w practice.new

Since % stands for the current filename, that line could also have
been typed:

:w %.new

5.5.4 Switching Files from vi
Since switching back to the previous file is something that
tends to happen a lot, you don't have to move to the ex command
line to do it. The vi command ^^ (the "control" key with the caret
key) will do this for you. Using this command is the same as typing
:e #. As with the :e command, if the current buffer has not been
saved, vi will not let you switch back to the previous file.

5.5.5 Edits Between Files
When you give a yank buffer a one-letter name, you have a
convenient way to move text from one file to another. Named
buffers are not cleared when a new file is loaded into the vi buffer
作者: projl    時(shí)間: 2008-06-11 14:34
with the :e command. Thus, by yanking or deleting text from one
file (into multiple named buffers if necessary), calling in a new file
with :e, and putting the named buffer(s) into the new file, you can
transfer material between files.

The following example illustrates how to transfer text from one file
to another.

Keystrokes Results
"f4yy
Yank four lines into buffer f.
:w
Save the file.
:e
letter
Enter the file letter with :e. Move the cursor to where the copied text
will be placed.
"fp
Place yanked text from named buffer f below the cursor.

Another way to move text from one file to another is to use the ex
commands :ya (yank) and :pu (put). These commands work the
same way as the equivalent vi commands y and p, but they are
used with ex's line-addressing capability and named buffers.

For example:

:160,224ya a

would yank (copy) lines 160 through 224 into buffer a. Next you
would move with :e to the file where you want to put these lines.
作者: projl    時(shí)間: 2008-06-11 14:35
Place the cursor on the line where you want to put the yanked lines.
Then type:

:pu
a
to put the contents of buffer a after the current line.
作者: projl    時(shí)間: 2008-06-11 14:35
Chapter 6. Global Replacement

Sometimes, halfway through a document or at the end of a draft,
you may recognize inconsistencies in the way that you refer to
certain things. Or, in a manual, some product whose name appears
throughout your file is suddenly renamed (marketing!). Often
enough it happens that you have to go back and change what
you've already written, and you need to make the changes in
several places.

The way to make these changes is with a powerful change
command called global replacement. With one command you can
automatically replace a word (or a string of characters) wherever it
occurs in the file.

In a global replacement, the ex editor checks each line of a file for a
given pattern of characters. On all lines where the pattern is found,
ex replaces the pattern with a new string of characters. For right
now, we'll treat the search pattern as if it were a simple string; later
in the chapter we'll look at the powerful pattern-matching language
known as regular expressions.

Global replacement really uses two ex commands: :g (global) and
:s (substitute). Since the syntax of global replacement commands
can get fairly complex, let's look at it in stages.

The substitute command has the syntax:

:s/old/new/

This changes the first occurrence of the pattern old to new on the
current line. The / (slash) is the delimiter between the various parts
of the command. (The slash is optional when it is the last character
on the line.)

A substitute command with the syntax:

:s/old/new/g

changes every occurrence of old to new on the current line, not just
the first occurrence. The :s command allows options following the
substitution string. The g option in the syntax above stands for
global. (The g option affects each pattern on a line; don't confuse it
with the :g command, which affects each line of a file.)
作者: projl    時(shí)間: 2008-06-11 14:36
By prefixing the :s command with addresses, you can extend its
range to more than one line. For example, this line will change
every occurrence of old to new from line 50 to line 100:

:50,100s/old/new/g

This command will change every occurrence of old to new within the
entire file:

:1,$s/old/new/g

You can also use % instead of 1,$ to specify every line in a file. Thus
the last command could also be given like this:

:%s/old/new/g

Global replacement is much faster than finding each instance of a
string and replacing it individually. Because the command can be
used to make many different kinds of changes, and because it is so
powerful, we will first illustrate simple replacements and then build
up to complex, context-sensitive replacements.

6.1 Confirming Substitutions
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 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!.

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

It 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

^^^_
作者: projl    時(shí)間: 2008-06-11 14:37
If you want to make the replacement, you must enter y (for yes)
and press RETURN. If you don't want to make a change, simply
press RETURN.[1]

[1] elvis 2.0 doesn't support this feature. In the other clones, the actual appearance and prompt differ, but
the effect is still the same, allowing you to choose whether or not to do the substitution in each case.
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:

/which Search for which.
cwthat ESC Change to that.
n Repeat search.
n Repeat search, skip a change.
. Repeat change (if appropriate).
.
.
.

6.2 Context-Sensitive Replacement
The simplest global replacements substitute one word (or a phrase)
for another. If you have typed a file with several misspellings
(editer for editor), you can do the global replacement:

:%s/editer/editor/g

This substitutes editor for every occurrence of editer throughout the
file.

There is a second, slightly more complex syntax for global
replacement. This syntax lets you search for a pattern, and then,
once you find the line with the pattern, make a substitution on a
string different from the pattern. You can think of this as context-
sensitive replacement.

The syntax is as follows:

:g/pattern/s/old/new/g
作者: projl    時(shí)間: 2008-06-11 14:37
The first g tells the command to operate on all lines of a file. pattern
identifies the lines on which a substitution is to take place. On those
lines containing pattern, ex is to substitute (s) for old the characters
in new. The last g indicates that the substitution is to occur globally
on that line.

For example, in this book, the SGML directives <keycap> and
</keycap> place a box around ESC to show the ESCAPE key. You
want ESC to be all in caps, but you don't want to change any
instances of Escape that might be in the text. To change instances
of Esc to ESC only when Esc is on a line that contains the <keycap>
directive, you could enter:

:g/<keycap>/s/Esc/ESC/g

If the pattern being used to find the line is the same as the one you
want to change, you don't have to repeat it. The command:

:g/string/s//new/g

would search for lines containing string and substitute for that same
string.

Note that:

:g/editer/s//editor/g

has the same effect as:

:%s/editer/editor/g

You can save some typing by using the second form. It is also
possible to combine the :g command with :d, :mo, :co and other ex
commands besides :s. As we'll show, you can thus make global
deletions, moves, and copies.

6.3 Pattern-Matching Rules
In making global replacements, UNIX editors such as vi allow you to
search not just for fixed strings of characters, but also for variable
patterns of words, referred to as regular expressions.

When you specify a literal string of characters, the search might
turn up other occurrences that you didn't want to match. The
problem with searching for words in a file is that a word can be used
in different ways. Regular expressions help you conduct a search for
words in context. Note that regular expressions can be used with
作者: projl    時(shí)間: 2008-06-11 14:38
the vi search commands / and ? as well as in the ex :g and :s
commands.

For the most part, the same regular expressions work with other

[2]
UNIX programs such as grep, sed, and awk.

[2] Much more information on regular expressions can be found in the two O'Reilly books sed & awk, by Dale
Dougherty and Arnold Robbins, and Mastering Regular Expressions, by Jeffrey E.F. Friedl.
Regular expressions are made up by combining normal characters

[3]
with a number of special characters called metacharacters. The

metacharacters and their uses are listed below.

[3] Technically speaking, we should probably call these metasequences, since sometimes two characters
together have special meaning, and not just single characters. Nevertheless, the term metacharacters is in
common use in UNIX literature, so we follow that convention here.
6.3.1 Metacharacters Used in Search Patterns
.

Matches any single character except a newline. Remember
that spaces are treated as characters. For example, p.pmatches character strings such as pep, pip, and pcp.

*

Matches zero or more (as many as there are) of the single
character that immediately precedes it. For example, bugs*
will match bugs (one s) or bug (no s's).

The * can follow a metacharacter. For example, since . (dot)
means any character, .* means "match any number of any
character."

Here's a specific example of this. The command
:s/End.*/End/ removes all characters after End (it replaces
the remainder of the line with nothing).

^

When used at the start of a regular expression, requires that
the following regular expression be found at the beginning of
the line; for example, ^Part matches Part when it occurs at
the beginning of a line, and ^... matches the first three
characters of a line. When not at the beginning of a regular
expression, ^ stands for itself.

$
作者: projl    時(shí)間: 2008-06-11 14:38
When used at the end of a regular expression, requires that
the preceding regular expression be found at the end of the
line; for example, here matches only when here: occurs at
the end of a line. When not at the end of a regular expression,
$ stands for itself.

\

Treats the following special character as an ordinary
character. For example, \. matches an actual period instead
of "any single character," and \* matches an actual asterisk
instead of "any number of a character." The \ (backslash)
prevents the interpretation of a special character. This
prevention is called "escaping the character." (Use \\ to get a
literal backslash.)

[ ]

Matches any one of the characters enclosed between the
brackets. For example, [AB] matches either A or B, and
p[aeiou]t matches pat, pet, pit, pot, or put. A range of
consecutive characters can be specified by separating the first
and last characters in the range with a hyphen. For example,
[A-Z] will match any uppercase letter from A to Z, and [0-9]
will match any digit from 0 to 9.

You can include more than one range inside brackets, and you
can specify a mix of ranges and separate characters. For
example, [:;A-Za-z()] will match four different punctuation
marks, plus all letters.

Most metacharacters lose their special meaning inside
brackets, so you don't need to escape them if you want to use
them as ordinary characters. Within brackets, the three
metacharacters you still need to escape are \-]. The hyphen
(-) acquires meaning as a range specifier; to use an actual
hyphen, you can also place it as the first character inside the
brackets.

A caret (^) has special meaning only when it is the first
character inside the brackets, but in this case the meaning
differs from that of the normal ^ metacharacter. As the first
character within brackets, a ^ reverses their sense: the
brackets will match any one character not in the list. For
example, [^a-z] matches any character that is not a
lowercase letter.
作者: projl    時(shí)間: 2008-06-11 14:39
\( \)

Saves the pattern enclosed between \( and \) into a special
holding space or "hold buffer." Up to nine patterns can be
saved in this way on a single line. For example, the pattern:

\(That\) or \(this\)

saves That in hold buffer number 1 and saves this in hold
buffer number 2. The patterns held can be "replayed" in
substitutions by the sequences \1 to \9. For example, to
rephrase That or this to read this or That, you could enter:

:%s/\(That\) or \(this\)/\2 or \1/

You can also use the \n notation within a search or substitute
string:

:s/\(abcd\)\1/alphabet-soup/

[4]
changes abcdabcd into alphabet-soup.

[4] This works with vi, nvi, and vim, but not with elvis 2.0, vile 7.4, or vile 8.0.
\< \>

Matches characters at the beginning (\<) or at the end (\>) of
a word. The end or beginning of a word is determined either
by a punctuation mark or by a space. For example, the
expression \<ac will match only words that begin with ac,
such as action. The expression ac\> will match only words
that end with ac, such as maniac. Neither expression will
match react. Note that unlike \(...\), these do not have to
be used in matched pairs.

~

Matches whatever regular expression was used in the last
search. For example, if you searched for The, you could
search for Then with /~n. Note that you can use this pattern
only in a regular search (with /).[5] It won't work as the
pattern in a substitute command. It does, however, have a
similar meaning in the replacement portion of a substitute
command.

[5] This is a rather flaky feature of the original vi. After using it, the saved search pattern is set to
the new text typed after the ~, not the combined new pattern, as one might expect. Also, none of
the clones behaves this way. So, while this feature exists, it has little to recommend its use.
作者: projl    時(shí)間: 2008-06-11 14:39
Several of the clones support optional, extended regular expression
syntaxes. See Section 8.4 for more information.

6.3.2 POSIX Bracket Expressions
We have just described the use of brackets for matching any one of
the enclosed characters, such as [a-z]. The POSIX standard
introduced additional facilities for matching characters that are not
in the English alphabet. For example, the French 貓 is an alphabetic
character, but the typical character class [a-z] would not match it.
Additionally, the standard provides for sequences of characters that
should be treated as a single unit when matching and collating
(sorting) string data.

POSIX also formalizes the terminology. Groups of characters within
brackets are called a "bracket expression" in the POSIX standard.
Within bracket expressions, beside literal characters such as a, !,
and so on, you can have additional components. These are:


作者: projl    時(shí)間: 2008-06-11 14:40
[:graph:] Printable and visible (non-space) characters
[:lower:] Lowercase characters
[:print:] Printable characters (includes whitespace)
[:punct:] Punctuation characters
[:space:] Whitespace characters
[:upper:] Uppercase characters
[digit:] Hexadecimal digits

You will have to do some research to determine if you have this
facility in your version of vi. You may need to use a special option to
enable POSIX compliance, have a particular environment variable
set, or use a version of vi that is in an unusual directory.

vi on HP-UX 9.x (and newer) systems support POSIX bracket
expressions, as does /usr/xpg4/bin/vi, on Solaris (but not
/usr/bin/vi). This facility is also available in nvi, and in elvis 2.1. As
commercial UNIX vendors become standards-compliant, expect to
see this feature become more widespread.

6.3.3 Metacharacters Used in Replacement Strings
When you make global replacements, the regular expressions above
carry their special meaning only within the search portion (the first
part) of the command.

For example, when you type this:

:%s/1\. Start/2. Next, start with $100/

note that the replacement string treats the characters . and $
literally, without your having to escape them. By the same token,
let's say you enter:

:%s/[ABC]/[abc]/g

If you're hoping to replace A with a, B with b, and C with c, you'll be
surprised. Since brackets behave like ordinary characters in a
replacement string, this command will change every occurrence of
A, B, or C to the five-character string [abc].

To solve problems like this, you need a way to specify variable
replacement strings. Fortunately, there are additional
metacharacters that have special meaning in a replacement string.

\ n
作者: projl    時(shí)間: 2008-06-11 14:41
Is replaced with text matched by the nth pattern previously
saved by \( and \), where n is a number from 1 to 9, and
previously saved patterns (kept in hold buffers) are counted
from the left on the line. See the explanation for \( and \)
earlier in this chapter.

\

Treats the following special character as an ordinary
character. Backslashes are metacharacters in replacement
strings as well as in search patterns. To specify a real
backslash, type two in a row (\\).

&

Is replaced with the entire text matched by the search pattern
when used in a replacement string. This is useful when you
want to avoid retyping text:

:%s/Yazstremski/&, Carl/

The replacement will say Yazstremski, Carl. The & can also
replace a variable pattern (as specified by a regular
expression). For example, to surround each line from 1 to 10
with parentheses, type:

:1,10s/.*/(&)/

The search pattern matches the whole line, and the &
"replays" the line, followed by your text.

~

Has a similar meaning as when it is used in a search pattern;
the string found is replaced with the replacement text
specified in the last substitute command. This is useful for
repeating an edit. For example, you could say
:s/thier/their/ on one line and repeat the change on
another with :s/thier/~/. The search pattern doesn't need
to be the same, though.

For example, you could say :s/his/their/ on one line and

[6]
repeat the replacement on another with :s/her/~/.

[6] Modern versions of the ed editor use % as the sole character in the replacement text to mean
"the replacement text of the last substitute command."
\u or \l
作者: projl    時(shí)間: 2008-06-11 14:41
Causes the next character in the replacement string to be
changed to uppercase or lowercase, respectively. For
example, to change yes, doctor into Yes, Doctor, you could
say:

:%s/yes, doctor/\uyes, \udoctor/

This is a pointless example, though, since it's easier just to
type the replacement string with initial caps in the first place.
As with any regular expression, \u and \l are most useful
with a variable string. Take, for example, the command we
used earlier:

:%s/\(That\) or \(this\)/\2 or \1/

The result is this or That, but we need to adjust the cases.
We'll use \u to uppercase the first letter in this (currently
saved in hold buffer 2); we'll use \l to lowercase the first
letter in That (currently saved in hold buffer 1):

:s/\(That\) or \(this\)/\u\2 or \l\1/

The result is This or that. (Don't confuse the number one with
the lowercase l; the one comes after.)

\U or \L and \e or \E

\U and \L are similar to \u or \l, but all following characters
are converted to uppercase or lowercase until the end of the
replacement string or until \e or \E is reached. If there is no
\e or \E, all characters of the replacement text are affected
by the \U or \L. For example, to uppercase Fortran, you could
say:

:%s/Fortran/\UFortran/

or, using the & character to repeat the search string:

:%s/Fortran/\U&/

All pattern searches are case-sensitive. That is, a search for the will
not find The. You can get around this by specifying both uppercase
and lowercase in the pattern:

/[Tt]he

You can also instruct vi to ignore case by typing :setic. See
Chapter 7, for additional details.
作者: projl    時(shí)間: 2008-06-11 14:42
6.3.4 More Substitution Tricks
You should know some additional important facts about the
substitute command:

1. A simple :s is the same as :s//~/. In other words, repeat the
last substitution. This can save enormous amounts of time
and typing when you are working your way through a
document making the same change repeatedly, but you don't
want to use a global substitution.
2. If you think of the & as meaning "the same thing" (as in what
was just matched), this command is relatively mnemonic. You
can follow the & with a g, to make the substitution globally on
the line, and even use it with a line range:
:%&g

repeat the last substitution everywhere

3. The & key can be used as a vi command to perform the :&
command, i.e., to repeat the last substitution. This can save
even more typing than :sRETURN; one keystroke versus
three.
4. The :~ command is similar to the :& command, but with a
subtle difference. The search pattern used is the last regular
expression used in any command, not necessarily the one
used in the last substitute command.
For example,[7] in the sequence:

[7] Thanks to Keith Bostic, in the nvi documentation, for this example.
:s/red/blue/
:/green
:
~


The :~ is equivalent to :s/green/blue/.

5. Besides the / character, you may use any non-alphanumeric,
non-whitespace character as your delimiter, except backslash,
double-quote, and the vertical bar (\, ", and |). This is
particularly handy when you have to make a change to a
pathname.
:%s;/user1/tim;/home/tim;g

6. When the edcompatible option is enabled, vi remembers the
flags (g for global and c for confirmation) used on the last
substitute, and applies them to the next one.
作者: projl    時(shí)間: 2008-06-11 14:42
This is most useful when you are moving through a file and
you wish to make global substitutions. You can make the first
change:

:s/old/new/g

:set edcompatible

After that, subsequent substitute commands will be global.

Despite the name, no known version of UNIX ed actually
works this way.

6.4 Pattern-Matching Examples
Unless you are already familiar with regular expressions, the
discussion of special characters above probably looks forbiddingly
complex. A few more examples should make things clearer. In the
examples that follow, a square ( ) is used to mark a space; it is not
a special character.

Let's work through how you might use some special characters in a
replacement. Suppose that you have a long file and that you want
to substitute the word child with the word children throughout that
file. You first save the edited buffer with :w, then try the global
replacement:

:%s/child/children/g

When you continue editing, you notice occurrences of words such as
childrenish. You have unintentionally matched the word childish.
Returning to the last saved buffer with :e!, you now try:

:%s/child

/children
/g

(Note that there is a space after child.) But this command misses
the occurrences child., child,, child: and so on. After some thought,
you remember that brackets allow you to specify one character
from among a list, so you realize a solution:

:%s/child[

,.;:!?]/children[
,.;:!?]/g
作者: projl    時(shí)間: 2008-06-11 14:43
This searches for child followed by either a space (indicated by ) or
any one of the punctuation characters ,.;:!?. You expect to
replace this with children followed by the corresponding space or
punctuation mark, but you've ended up with a bunch of punctuation
marks after every occurrence of children. You need to save the
space and punctuation marks inside a \( and \). Then you can
"replay" them with a \1. Here's the next attempt:

:%s/child\([


,.;:!?]\)/children\1/g

When the search matches a character inside the \( and \), the \1
on the right-hand side restores the same character. The syntax may
seem awfully complicated, but this command sequence can save
you a lot of work! Any time you spend learning regular expression
syntax will be repaid a thousandfold!

The command is still not perfect, though. You've noticed that
occurrences of Fairchild have been changed, so you need a way to
match child when it isn't part of another word.

As it turns out, vi (but not all other programs that use regular
expressions) has a special syntax for saying "only if the pattern is a
complete word." The character sequence \< requires the pattern to
match at the beginning of a word, whereas \> requires the pattern
to match at the end of a word. Using both will restrict the match to
a whole word. So, in the task given above, \<child\> will find all
instances of the word child, whether followed by punctuation or
spaces. Here's the substitution command you should use:

:%s/\<child\>/children/g

6.4.1 Search for General Class of Words
Suppose your subroutine names begin with the prefixes: mgi, mgr,
and mga.


If you want to save the prefixes, but want to change the name box
to square, either of the following replacement commands will do the
trick. The first example illustrates how \( and \) can be used to
save whatever pattern was actually matched. The second example
shows how you can search for one pattern but change another:
作者: projl    時(shí)間: 2008-06-11 14:43
:g/mg\([ira]\)box/s//mg\1square/g

The global replacement keeps track of whether an i, r or a is saved. In that way,
box is changed to square only when box is part of the routine's name.
:g/mg[ira]box/s/box/square/g

This has the same effect as the previous command, but it is a little less safe
since it could change other instances of box on the same line, not just those
within the routine names.
6.4.2 Block Move by Patterns
You can also move blocks of text delimited by patterns. For
example, assume you have a 150-page reference manual. Each
page is organized into three paragraphs with the same three
headings: SYNTAX, DESCRIPTION, and PARAMETERS. A sample of
one reference page follows:

.Rh 0 "Get status of named file" "STAT"
.Rh "SYNTAX"
.nf
integer*4 stat, retvalinteger*4 status(11)
character*123 filename
...
retval = stat (filename, status)
.fi
.Rh "DESCRIPTION"
Writes the fields of a system data structure into thestatus array.
These fields contain (among otherthings) information about the file's location, accessprivileges, owner, and time of last modification.
.Rh "PARAMETERS"
.IP "\fBfilename\fR" 15n
A character string variable or constant containingthe UNIX pathname for the file whose status you wantto retrieve.
You can give the ...

Suppose that it is decided to move DESCRIPTION above the
SYNTAX paragraph. With pattern matching, you can move blocks of
text on all 150 pages with one command!

:g /SYNTAX/.,/DESCRIPTION/-1 move /PARAMETERS/-1
作者: projl    時(shí)間: 2008-06-11 14:44
This command works as follows. First, ex finds and marks each line
that matches the first pattern (i.e., that contains the word SYNTAX).
Second, for each marked line, it sets . (dot, the current line) to that
line, and executes the command. Using the move command, the
command moves the block of lines from the current line (dot) to the
line before the one containing the word DESCRIPTION
(/DESCRIPTION/-1) to just before the line containing PARAMETERS
(/PARAMETERS/-1).

Note that ex can place text only below the line specified. To tell ex
to place text above a line, you first subtract one with -1, and then
ex places your text below the previous line. In a case like this, one
command saves literally hours of work. (This is a real-life example鈥
作者: projl    時(shí)間: 2008-06-11 14:45
A slash (used as a delimiter in the global replacement
sequence) must be escaped with a backslash when it is part of
the pattern or replacement; use \/ to get /. An alternate way
to achieve this same effect is to use a different character as
the pattern delimiter. For example, you could make the above
replacement using colons as delimiters. (The delimiter colons
and the ex command colon are separate entities.) Thus:

:%s:/home/tim:/home/linda:g

This is much more readable.

3. Put HTML italicization codes around the word RETURN:
:%s:RETURN:<I>&</I>:g

Notice here the use of & to represent the text that was
actually matched, and, as just described, the use of colons as
delimiters instead of slashes.

4. Change all periods to semicolons in lines 1 to 10:
:1,10s/\./;/g

A dot has special meaning in regular expression syntax and
must be escaped with a backslash (\.).

5. Change all occurrences of the word help (or Help) to HELP:
:%s/[Hh]elp/HELP/g

or:

:%s/[Hh]elp/\U&/g

The \U changes the pattern that follows to all uppercase. The
pattern that follows is the repeated search pattern, which is
either help or Help.

6. Replace one or more spaces with a single space:
:%s/


*
/



/g
作者: projl    時(shí)間: 2008-06-11 14:45
Make sure you understand how the asterisk works as a special
character. An asterisk following any character (or following
any regular expression that matches a single character, such
as . or [a-z]) matches zero or more instances of that
character. Therefore, you must specify two spaces followed by
an asterisk to match one or more spaces (one space, plus
zero or more spaces).

7. Replace one or more spaces following a colon with two
spaces:
:%s/:


*/
:



/g

8. Replace one or more spaces following a period or a colon with
two spaces:
:%s/\([:.]\)


*/\
1



/g

Either of the two characters within brackets can be matched.
This character is saved into a hold buffer, using \( and \),
and restored on the right-hand side by the \1. Note that
within brackets a special character such as a dot does not
need to be escaped.

9. Standardize various uses of a word or heading:
:%s/^Note[
:s]*/Notes:


/g

The brackets enclose three characters: a space, a colon, and
the letter s. Therefore, the pattern Note[ s:] will match
Note , Notes or Note:. An asterisk is added to the pattern so
that it also matches Note (with zero spaces after it) and
Notes: (the already correct spelling). Without the asterisk,
作者: projl    時(shí)間: 2008-06-11 14:46
Note would be missed entirely and Notes: would be incorrectly
changed to Notes: :.

10. Delete all blank lines:
:g/^$/d

What you are actually matching here is the beginning of the
line (^) followed by the end of the line ($), with nothing in
between.

11.
Delete all blank lines, plus any lines that contain only
whitespace:
:g/^[


tab]*$/d

(In the line above, a tab is shown as tab.) A line may appear
to be blank, but may in fact contain spaces or tabs. The
previous example will not delete such a line. This example,
like the one above it, searches for the beginning and end of
the line. But instead of having nothing in between, the pattern
tries to find any number of spaces or tabs. If no spaces or
tabs are matched, the line is blank. To delete lines that
contain whitespace but that aren't empty, you would have to
match lines with at least one space or tab:

:g/^[


tab][


tab]*$/d

12. Delete all leading spaces on every line:
:%s/^


*\(.*\)/\1/

Use ^* to search for one or more spaces at the beginning
of each line; then use \(.*\) to save the rest of the line into
the first hold buffer. Restore the line without leading spaces,
using \1.

13. Delete all spaces at the end of every line:
:%s/\(.*\)
作者: projl    時(shí)間: 2008-06-11 14:46
*$/\1/

For each line, use \(.*\) to save all the text on the line, but
only up until one or more spaces at the end of the line.
Restore the saved text without the spaces.

The substitutions in this example and the previous one will
happen only once on any given line, so the g option doesn't
need to follow the replacement string.

14. Insert a > at the start of every line in a file:
:%s/^/>

/

What we're really doing here is "replacing" the start of the line
with > . Of course, the start of the line (being a logical
construct, not an actual character) isn't really replaced!

This command is useful when replying to mail or USENET
news postings. Frequently, it is desirable to include part of the
original message in your reply. By convention, the inclusion is
distinguished from your reply by setting off the included text
with a right angle bracket and a couple of spaces at the start
of the line. This can be done easily as shown above.
(Typically, only part of the original message will be included.
Unneeded text can be deleted either before or after the above
replacement.) Advanced mail systems do this automatically.
However, if you're using vi to edit your mail, you can do it
with this command.

15. Add a period to the end of the next six lines:
:.,+5s/$/./

The line address indicates the current line plus five lines. The
$ indicates the end of line. As in the previous example, the $
is a logical construct. You aren't really replacing the end of the
line.

16.
Reverse the order of all hyphen-separated items in a
list:
:%s/\(.*\)
作者: projl    時(shí)間: 2008-06-11 14:47
-



\(.*\)/\
2



-



-
\1/

Use \(.*\) to save text on the line into the first hold buffer,
but only until you find . Then use \(.*\) to save the rest
of the line into the second hold buffer. Restore the saved
portions of the line, reversing the order of the two hold
buffers. The effect of this command on several items is shown
below.

more - display files

becomes:

display files - more

and:

lp - print files

becomes:

print files - lp

17. Change every word in a file to uppercase:
:%s/.*/\U&/

or:

:%s/./\U&/g

The \U flag at the start of the replacement string tells vi to
change the replacement to uppercase. The & character replays
the text matched by the search pattern as the replacement.
These two commands are equivalent; however, the first form
is considerably faster, since it results in only one substitution
per line (.* matches the entire line, once per line), whereas
the second form results in repeated substitutions on each line
(. matches only a single character, with the replacement
repeated on account of the trailing g).
作者: projl    時(shí)間: 2008-06-11 14:47
18. Reverse the order of lines in a file:[8]
[8] From an article by Walter Zintz in UNIX World, May 1990.
:g/.*/mo0

The search pattern matches all lines (a line contains zero or
more characters). Each line is moved, one by one, to the top
of the file (that is, moved after imaginary line 0). As each
matched line is placed at the top, it pushes the previously
moved lines down, one by one, until the last line is on top.
Since all lines have a beginning, the same result can be
achieved more succinctly:

:g/^/mo0

19.
In a database, on all lines not marked Paid in full,
append the phrase Overdue:
:g!/Paid


in


full/s/$/Overdue/

or the equivalent:

:v/Paid
in


full/s/$/Overdue/

To affect all lines except those matching your pattern, add a !
to the g command, or simply use the v command.

20.
For any line that doesn't begin with a number, move the
line to the end of the file:
:g!/^[0-9]/m$

or:

:g/^[^0-9]/m$

As the first character within brackets, a caret negates the
sense, so the two commands have the same effect. The first
one says, "Don't match lines that begin with a number," and
作者: projl    時(shí)間: 2008-06-11 14:48
the second one says, "Match lines that don't begin with a
number."

21.
Change manually numbered section heads (e.g., 1.1,
1.2, etc.) to a troff macro (e.g., .Ah for an A-level heading):
:%s/^[1-9]\.[1-9]/.Ah/

The search string matches a digit other than zero, followed by
a period, followed by another non-zero digit. Notice that the
period doesn't need to be escaped in the replacement (though
a \ would have no effect, either). The command above won't
find chapter numbers containing two or more digits. To do so,
modify the command like this:

:%s/^[1-9][0-9]*\.[1-9]/.Ah/

Now it will match chapters 10 to 99 (digits 1 to 9, followed by
a digit), 100 to 999 (digits 1 to 9, followed by two digits), etc.
The command still finds chapters 1 to 9 (digits 1 to 9,
followed by no digit).

22.
Remove numbering from section headings in a
document. You want to change the sample lines:
23. 2.1 Introduction
10.3.8 New Functions
into the lines:

Introduction
New Functions


Here's the command to do this:

:%s/^[1-9][0-9]*\.[1-9][0-9.]
*
/
/



The search pattern resembles the one in the previous
example, but now the numbers vary in length. At a minimum,
the headings contain number, period, number, so you start
with the search pattern from the previous example:

[1-9][0-9]*\.[1-9]

But in this example, the heading may continue with any
number of digits or periods:


[0-9.]*
作者: projl    時(shí)間: 2008-06-11 14:49
of
24.
Change the word Fortran to the phrase FORTRAN
(acronym of FORmula TRANslation)
:
:%s/\(For\)\(tran\)/\U\1\2\E

(acronym

\U\1\Emula

\U\2\Eslation)/g

First, since we notice that the words FORmula and
TRANslation use portions of the original word, we decide to
save the search pattern in two pieces: \(For\) and \(tran\).
The first time we restore it, we use both pieces together,
converting all characters to uppercase: \U\1\2. Next, we
undo the uppercase with \E; otherwise the remaining
replacement text would all be uppercase. The replacement
continues with actual typed words, then we restore the first
hold buffer. This buffer still contains For, so again we convert
to uppercase first: \U\1. Immediately after, we lowercase the
rest of the word: \Emula. Finally, we restore the second hold
buffer. This contains tran, so we precede the "replay" with
uppercase, follow it with lowercase, and type out the rest of
the word: \U\2\Eslation).

6.5 A Final Look at Pattern Matching
We conclude this chapter by presenting sample tasks that involve
complex pattern-matching concepts. Rather than solve the
problems right away, we'll work toward the solutions step by step.

6.5.1 Deleting an Unknown Block of Text
Suppose you have a few lines with this general form:

the best of times; the worst of times: movingThe coolest of times; the worst of times: moving

The lines that you're concerned with always end with moving, but
you never know what the first two words might be. You want to
change any line that ends with moving to read:

The greatest of times; the worst of times: moving
作者: projl    時(shí)間: 2008-06-11 14:49
Since the changes must occur on certain lines, you need to specify a
context-sensitive global replacement. Using :g/moving$/ will match
lines that end with moving. Next, you realize that your search
pattern could be any number of any character, so the
metacharacters .* come to mind. But these will match the whole
line unless you somehow restrict the match. Here's your first
attempt:

:g/moving$/s/.*of/The

greatest
of/

This search string, you decide, will match from the beginning of the
line to the first of. Since you needed to specify the word of to
restrict the search, you simply repeat it in the replacement. Here's
the resulting line:

The greatest of times: moving

Something went wrong. The replacement gobbled the line up to the
second of instead of the first. Here's why. When given a choice, the
action of "match any number of any character" will match as much
text as possible. In this case, since the word of appears twice, your
search string finds:

the best of times; the worst of

rather than:

the best of

Your search pattern needs to be more restrictive:

:g/moving$/s/.*of times;/The greatest of times;/

Now the .* will match all characters up to the instance of the
phrase of times;. Since there's only one instance, it has to be the
first.

There are cases, though, when it is inconvenient, or even incorrect,
to use the .* metacharacters. For example, you might find yourself
typing many words to restrict your search pattern, or you might be
unable to restrict the pattern by specific words (if the text in the
lines varies widely). The next section presents such a case.
作者: projl    時(shí)間: 2008-06-11 14:50
6.5.2 Switching Items in a Database
Suppose you want to switch the order of all last names and first
names in a (text) database. The lines look like this:

Name: Feld, Ray; Areas: PC, UNIX; Phone: 123-4567Name: Joy, Susan S.; Areas: Graphics; Phone: 999-3333

The name of each field ends with a colon, and each field is
separated by a semicolon. Using the top line as an example, you
want to change Feld, Ray to Ray Feld. We'll present some
commands that look promising but don't work. After each
command, we show you the line the way it looked before the
change and after the change.

:%s/: \(.*\), \(.*\);/: \2 \1;/

Name: Feld, Ray; Areas: PC, UNIX; Phone: 123-4567Before

Name: UNIX Feld, Ray; Areas: PC; Phone: 123-4567After

We've highlighted the contents of the first hold buffer in bold and
the contents of the second hold buffer in italic. Note that the first
hold buffer contains more than you want. Since it was not
sufficiently restricted by the pattern that follows it, the hold buffer
was able to save up to the second comma. Now you try to restrict
the contents of the first hold buffer:

:%s/: \(....\), \(.*\);/: \2 \1;/

Name: Feld, Ray; Areas: PC, UNIX; Phone: 123-4567Before

Name: Ray; Areas: PC, UNIX Feld; Phone: 123-4567After

Here you've managed to save the last name in the first hold buffer,
but now the second hold buffer will save anything up to the last
semicolon on the line. Now you restrict the second hold buffer, too:

:%s/: \(....\), \(...\);/: \2 \1;/

Name: Feld, Ray; Areas: PC, UNIX; Phone: 123-4567Before

Name: Ray Feld; Areas: PC, UNIX; Phone: 123-4567After




歡迎光臨 Chinaunix (http://www.72891.cn/) Powered by Discuz! X3.2