2. More Vim commands
2.1 Deleting text
-
To delete text in Vim we can use the commands
x
, which deletes the character at the cursor, andd
.1G5w
-
Press
x
a few times to delete a few characters, then pressu
several times to undo.Press
3x
to delete 3 chars, thenu
to undo. -
Try also these and see what they do:
dW
andu
5dW
andu
d$
andu
d0
andu
dd
andu
3dd
andu
dG
andu
d4G
andu
2.2 Cut, copy and paste
-
When we delete some text, it is actually like cut, because the deleted part is placed on a paste buffer and can be placed somewhere else. To paste it after the cursor we can use the command
p
, to paste it before the cursor we can use capitalP
. -
Try:
5x
andp
, thenuu
3x
andP
, thenuu
5dw
,$
,p
,uu
d$
,0
,p
,u
,P
,uu
dd
,p
,u
,P
,uu
-
Instead of
d
we can use the commandy
(yank) to copy text.yw
,p
,u
,P
,u
5yw
,P
,u
yy
,p
,u
3yy
,P
,u
,p
,u
yG
,P
,u
y$
,0
,P
,u
-
To join a line with the next one we can use
J
:3G
,J
,J
,uu
2.3 Search and replace
-
To find a character in the current line, press
f
and the character:1G
,fa
,;
-
To move the cursor to the next occurrence of a word or phrase, the
/
command is used. Type a word or phrase after it and then Enter:/
then typeLine
To find the next match press
n
:n
,n
,n
-
To replace (substitute)
Line
byline
in the whole file use::% s/Line/line/g
It is similar to the
sed
command. It starts with a range of lines where to perform the substitution. In this example,%
denotes the whole file and is the same as1,$
(from the first line to the last one). -
We can also ask for confirmation by adding the modifier
c
at the end::1,$ s/line/Line/gc
The confirmation options are:
y
-- yesn
-- noa
-- allq
-- quitl
-- last (replace this one and quit)Ctrl-e
/Ctrl-y
-- scroll down and up, to see the context