Skip to main content

2. More Vim commands

2.1 Deleting text

  1. To delete text in Vim we can use the commands x, which deletes the character at the cursor, and d.

    1G5w

  2. Press x a few times to delete a few characters, then press u several times to undo.

    Press 3x to delete 3 chars, then u to undo.

  3. Try also these and see what they do:

    • dW and u
    • 5dW and u
    • d$ and u
    • d0 and u
    • dd and u
    • 3dd and u
    • dG and u
    • d4G and u

2.2 Cut, copy and paste

  1. 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 capital P.

  2. Try:

    5x and p, then uu

    3x and P, then uu

    5dw, $, p, uu

    d$, 0, p, u, P, uu

    dd, p, u, P, uu

  3. Instead of d we can use the command y (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

  4. To join a line with the next one we can use J:

    3G, J, J, uu

2.3 Search and replace

  1. To find a character in the current line, press f and the character:

    1G, fa, ;

  2. 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 type Line

    To find the next match press n:

    n, n, n

  3. To replace (substitute) Line by line 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 as 1,$ (from the first line to the last one).

  4. We can also ask for confirmation by adding the modifier c at the end:

    :1,$ s/line/Line/gc

    The confirmation options are:

    • y -- yes
    • n -- no
    • a -- all
    • q -- quit
    • l -- last (replace this one and quit)
    • Ctrl-e / Ctrl-y -- scroll down and up, to see the context
Loading asciinema cast...