ubuntu, updated

Vim: survival basics

Modes, open, save and quit, moving around and editing in vim. The minimum you need to edit a config file without panic.

Why vim?

vi/vim is on every Linux server, also on minimal systems and in rescue mode where nano may be missing. You don’t need to love it, but you should be able to edit a file with it. On Ubuntu, vi starts vim.

Tip: Prefer something simpler? nano is installed on Ubuntu too. Make it the default for sudoedit, visudo and crontab -e with sudo update-alternatives --config editor.

The one idea: modes

Vim has modes. Keys do different things depending on the mode. Most confusion comes from typing while in the wrong mode.

ModeYou are here when…Get there with
Normalyou move around and give commands (start mode)Esc (press it whenever you’re lost)
Insertyou type texti (before cursor), a (after), o (new line below)
Visualyou select textv (characters), V (lines), Ctrl+V (block)
Command lineyou type : commands at the bottom: from normal mode

The bottom line shows -- INSERT -- or -- VISUAL -- when you’re not in normal mode.

Open, save, quit

WhatKeys
Open a filevim /etc/hosts (root-owned: sudoedit /etc/hosts)
Open at line 42vim +42 file
Save:w
Save and quit:wq or ZZ
Quit (no changes):q
Quit and discard changes:q!
Save a root-owned file you opened without sudo:w !sudo tee %, then :q!

Moving around (normal mode)

KeysMoves
h j k lleft, down, up, right (arrow keys work too)
w / bnext / previous word
0 / $start / end of line
gg / Gfirst / last line
42G or :42line 42
Ctrl+D / Ctrl+Uhalf a page down / up
%jump to the matching bracket

Editing (normal mode)

KeysDoes
xdelete the character under the cursor
dddelete (cut) the line
dwdelete to the end of the word
Ddelete to the end of the line
cwchange the word (delete and go to insert mode)
r + charreplace one character
uundo
Ctrl+Rredo
.repeat the last change
>> / <<indent / unindent the line

Numbers repeat a command: 3dd deletes 3 lines, 5j moves 5 lines down.

Learn more

Run vimtutor. It is installed with vim and takes about 30 minutes.

Next: Vim: copy and paste.

§ home
~/knubertus/home/
1,1 Top