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
xa few times to delete a few characters, then pressuseveral times to undo.Press
3xto delete 3 chars, thenuto undo. -
Try also these and see what they do:
dWandu5dWandud$andud0anduddandu3ddandudGandud4Gandu
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:
5xandp, thenuu3xandP, thenuu5dw,$,p,uud$,0,p,u,P,uudd,p,u,P,uu -
Instead of
dwe can use the commandy(yank) to copy text.yw,p,u,P,u5yw,P,uyy,p,u3yy,P,u,p,uyG,P,uy$,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
fand 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 typeLineTo find the next match press
n:n,n,n -
To replace (substitute)
Linebylinein the whole file use::% s/Line/line/gIt is similar to the
sedcommand. 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
cat the end::1,$ s/line/Line/gcThe 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