How to open a file, make a change, save and quit; moving around, copying, searching and replacing in vim.
Contents
vi or vim is available on almost every server, so it is worth knowing the basics. If vim feels unfamiliar, you can edit files in nano instead: nano file — the key hints are shown at the bottom of the screen. If nano is not installed, run sudo apt install nano or sudo dnf install nano.
Modes
You open a file with vim file in normal mode: here the keys are commands (moving, deleting, copying), not text. To type, switch to insert mode:
i— insert before the cursor,a— insert after it;o— a new line below,O— a new line above.
Esc takes you back to normal mode — if you get lost, press it a couple of times. A colon in normal mode opens the command line at the bottom of the screen: saving, quitting, replacing.
Save and quit
:w | save |
:wq or :x | save and quit |
:q | quit, if there are no changes |
:q! | quit without saving |
:w !sudo tee % >/dev/null | save a file that you opened without sudo and cannot write to |
Moving around
arrow keys or h j k l | left, down, up, right |
w / b | forward / back one word |
0 / $ | start / end of the line |
gg / G | start / end of the file |
:42 or 42G | line 42 |
| Ctrl+F / Ctrl+B | page down / up |
Deleting, copying and pasting
x | delete the character under the cursor |
dd, 5dd | delete a line, five lines (what you delete can be pasted) |
dw | delete a word |
yy, 5yy | copy a line, five lines |
p / P | paste below / above |
J | join the line with the next one |
u / Ctrl+R | undo / redo |
Searching and replacing
/text | search forwards; n — next match, N — previous match |
:s/old/new/g | replace all matches in the current line |
:%s/old/new/g | replace throughout the file |
:%s/old/new/gc | the same, asking for confirmation of each replacement |
:10,20s/^/#/ | comment out lines 10 to 20 |
Useful settings
:set number / :set nonumber | show / hide line numbers |
:set paste | paste text from the clipboard without a “staircase” of indentation; afterwards, run :set nopaste |
:syntax on | syntax highlighting |
Didn’t find the answer? Ask our support team — we’ll help.