Deletion Commands

Now that you know how to enter commands and move around the line, you need to know how to delete. The basic deletion command in vi-mode is d followed by one other letter. This letter determines what the unit and direction of deletion is, and it corresponds to a motion command, as listed previously in Table 2-8.

Table 2-10 shows some commonly used examples.

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Table 2-10. Some vi-mode deletion commands

Command

Description

dh

Delete one character backwards

dl

Delete one character forwards

db

Delete one word backwards

dw

Delete one word forwards

dB

Delete one non-blank word backwards

dW

Delete one non-blank word forwards

d$

Delete to end of line

d0

Delete to beginning of line

These commands have a few variations and abbreviations. If you use a c instead of d, you will enter input mode after it does the deletion. You can supply a numeric repeat count either before or after the d (or c). Table 2-11 lists the available abbreviations.

Table 2-11. Abbreviations for vi-mode delete commands

Command

Description

D

Equivalent to d$ (delete to end of line)

dd

Equivalent to 0d$ (delete entire line)

C

Equivalent to c$ (delete to end of line, enter input mode)

cc

Equivalent to 0c$ (delete entire line, enter input mode)

X

Equivalent to dl (delete character backwards)

x

Equivalent to dh (delete character forwards)

Most people tend to use D to delete to end of line, dd to delete an entire line, and x (as "backspace") to delete single characters. If you aren't a hardcore vi user, you may find it difficult to make sure the more esoteric deletion commands are at your fingertips.

Every good editor provides "un-delete" commands as well as delete commands, and vi-mode is no exception. vi-mode maintains a delete buffer that stores all of the modifications to text on the current line only (note that this is different from the full vi editor). The command u undoes previous text modifications. If you type u, it will undo the last change. Typing it again will undo the change before that. When there are no more undo's, bash will beep. A related command is . (dot), which repeats the last text modification command.

There is also a way to save text in the delete buffer without having to delete it in the first place: just type in a delete command but use y ("yank") instead of d. This does not modify anything, but it allows you to retrieve the yanked text as many times as you like later on. The commands to retrieve yanked text are p, which inserts the text on the current line to the right of the cursor, and P, which inserts it to the left of the cursor. The y, p, and P commands are powerful but far better suited to "real vi" tasks like making global changes to documents or programs than to shell commands, so we doubt you'll use them very often.