You are logged in to a server over SSH, you need to fix a configuration
file, and the only editor available is vi. To get out right away: press
Esc once or twice, then type :wq followed by Enter to save and exit,
or :q! followed by Enter to exit and discard the changes. This guide
then teaches you to open a file, edit it and save it with vi, step by step:
the three modes, keyboard movement, deleting, copying, searching and
replacing. You will leave with the reflexes to edit any text file on a minimal
Linux system, an Alpine container or a server in rescue mode included.
What you will learn
- Open, edit and exit vi (the absolute basics)
- The system of modes that makes vi unique
- Move quickly around a file
- Search and replace text
What is vi?
vi (its name abbreviates the visual command) is a command-line text
editor created in 1976 by Bill Joy. It is present on almost every Unix and
Linux system, including emergency servers and Alpine images (through
BusyBox). A few very small container images ship no editor at all: check with
which vi, as shown below.
vi covers the bare essentials: open a file, move around it, edit it, save it. It provides no syntax highlighting and no plugins, and its settings stay rudimentary: those features belong to vim. In return, it starts on a system in rescue mode, in a BusyBox image or on an embedded device, where no other editor is installed.
| Characteristic | vi | Graphical editor (VS Code, etc.) |
|---|---|---|
| Availability | Everywhere, even without a desktop | Requires a graphical environment |
| Weight | Light | Much larger |
| Learning curve | Steep at first, then fast | Intuitive from the start |
| Typical use | Server troubleshooting, quick edits | Everyday development |
This table explains why vi survives far more comfortable editors: its
availability depends on nothing. Even if you work in VS Code or in
nano
every day, four situations will bring you back to it. A server booted in
rescue mode, where no other editor is installed. A container built on
an Alpine image, which ships vi (the BusyBox one) and nothing else. An SSH
connection to a network device or an embedded system. And finally
emergency troubleshooting, where installing an extra package is either
impossible or a bad idea on a production machine. In these four cases, knowing
how to type i, Esc and :wq makes the difference between fixing the file
and calling someone else.
Prerequisites
You need nothing more than a terminal and a few minutes. Before starting, check that vi is there, which it almost always is:
- A Linux terminal (physical, VM or WSL)
- No prior knowledge of vi
To check that vi is available on your system:
which viThe expected result is a path, for example /usr/bin/vi. If the command
prints nothing, no vi is installed on this system.
Knowing which program hides behind this path matters, because two different
programs answer to the name vi depending on the system, and they do not
behave the same way. This command gives the answer:
readlink -f "$(command -v vi)"On Debian 13, apt-cache show ranks vim-tiny at priority important and
vim at priority optional (version 2:9.1.1230-2+deb13u2 for both). A
standard installation therefore installs vim-tiny, a reduced version of Vim,
and not vim. Called under the name vi, vim-tiny reads the file
/etc/vim/vimrc.tiny, which contains set compatible: it then imitates the
original vi.
/usr/bin/vim.tinyIn this mode, the options are compatible, noshowmode and
undolevels=1000. You will see it in three places in this guide: the
-- INSERT -- indicator does not appear, u works as a toggle, and the arrow
keys typed in insert mode do not move the cursor. To get the behaviour of Vim,
install the full package with sudo apt install vim. The same test then gives
another result:
readlink -f "$(command -v vi)"vi --version | head -2/usr/bin/vim.basicVIM - Vi IMproved 9.1 (2024 Jan 02, compiled Nov 04 2026 22:12:34)Included patches: 1-948, 950-1230, 1242, 1244On Ubuntu 26.04.1, /usr/bin/vi also leads to /usr/bin/vim.basic (vim
package 2:9.1.2141-1ubuntu4.10, patches 1-948 and 950-2141). On AlmaLinux 10.2,
/usr/bin/vi is the binary of the vim-minimal package
(vim-minimal-9.1.083-9.el10_2.22):
/usr/bin/viVIM - Vi IMproved 9.1 (2024 Jan 02, compiled Sep 29 2026 00:00:00)Included patches: 1-83With Vim (vim package on Debian 13 and Ubuntu 26.04.1, vim-minimal on
AlmaLinux 10.2), vi is therefore Vim 9.1 and not the vi of 1976. It starts in
nocompatible mode (:set compatible? answers nocompatible), with
undolevels=1000 and showmode. The behaviours described below for
-- INSERT --, u and the arrow keys are those of this Vim. vim-tiny, the
historical vi and vim -C behave differently, and the page points it out at
each place concerned. In a container image, vi may be absent or be another
program: the readlink command above tells you what it is on your system.
First contact: open, write, save
Before learning all the commands, let's start with the only thing that matters when you discover vi: the full cycle of "open a file, type some text, save and exit".
"How do I get out of vi?" is the first question most beginners ask. You have the short answer at the top of the page; the sequence below puts it back in context, from the open file to the file written to disk.
-
Open vi on a test file
Create a temporary file to practise without risk:
Terminal window vi /tmp/test-vi.txtVi opens. The screen shows tildes (
~) on empty lines. You are in command mode: the keys on the keyboard do not write text, they trigger actions. -
Switch to insert mode to write
Press the
ikey (as in insert). You are now in insert mode: you can type text normally. If yourvidisplays the modes,-- INSERT --appears at the bottom of the screen; on Debian 13 withvim-tiny, nothing is displayed, and that is normal.Type a few lines:
This is my first file edited with vi.Line number two.And a third line to practise. -
Go back to command mode
Press the
Esckey. If-- INSERT --was displayed, it disappears. You are back in command mode. -
Save and exit
Type
:wqthen pressEnter.:opens Ex mode (the command line at the bottom of the screen)wmeans write (save)qmeans quit
-
Check that the file was saved
Back in the terminal, show the contents of the file:
Terminal window cat /tmp/test-vi.txtYou should see your three lines of text.
Repeat this sequence three times in a row before going on. The goal is not
to understand, it is to make the cycle i → text → Esc → :wq
automatic. It is the move you will repeat at every intervention on a
server, often in a context where your attention is elsewhere, on the incident
you are handling.
Here is an animated demonstration of this full cycle:

Exit vi in every situation
All these commands are typed from command mode, so after an Esc.
The logic fits in three letters: w writes the file to disk, q closes the
editor, and the exclamation mark ! forces the operation despite a
refusal. Without the !, vi blocks the exit if the buffer contains unsaved
changes: that is a protection, not a bug. Look at the middle column of the
table: it is what you will type, and the third column says what you lose or
keep.
| Situation | Command | What it does |
|---|---|---|
| Save and exit | :wq then Enter | Writes the file and closes vi |
| Exit without saving | :q! then Enter | Discards the changes |
| Just save | :w then Enter | Writes the file, stays in vi |
| Just exit (nothing to save) | :q then Enter | Closes vi (fails if there are unsaved changes) |
| Save + exit shortcut | ZZ (upper case, no :) | Equivalent to :wq |
| Save under another name | :w new_name | Creates a copy of the file |
| Exit every open file | :qa! | Closes everything without saving |
How do the modes of vi work?
Unlike nano or a graphical editor, vi does not work in "type text" mode by default. That is what confuses beginners.
The mechanism is as follows: vi keeps an internal state, the mode, and
interprets each key on the keyboard according to that state. In command
mode, the d key triggers a deletion; in insert mode, the same d key
writes the letter "d" into the file. These are not two different keyboards: it
is the same keystroke routed to two distinct tables of actions.
This design explains the beginner's classic mishap: they open a file, type
their text without having pressed i, and trigger a dozen random
commands. Nothing is lost for all that: u undoes, and :q! closes the
file without writing anything to disk.
This separation looks restrictive, but it gives access to far more commands than
a modeless editor: in command mode, every key on the keyboard
is a shortcut, with no modifier key. Where a graphical editor needs a
combination such as Ctrl+Shift+K to delete a line, vi asks for dd, two
strokes on the home row. That is what makes the editor very fast once the
moves are learnt, and also what makes it confusing for the first few hours.
The three modes
Read this table from the right-hand column first: knowing how to leave a
mode matters more than knowing how to enter it, because being stuck always
comes from a mode whose exit you do not know. Note also that only one mode,
command mode, can be reached from the other two. That is why a repeated
Esc is the universal emergency move.
| Mode | How to enter it | What it does | How to leave it |
|---|---|---|---|
| Command | Esc (or on opening) | Move, delete, copy, paste | Type i, a, o or : |
| Insert | i, a, o, O | Write text | Press Esc |
| Ex | : (from command mode) | Long commands (:w, :q, :%s/…) | Enter to run, Esc to cancel |
Command mode is the mandatory crossing point: you never switch directly
from insert mode to Ex mode, you have to go back through it. Get into the
habit of pressing Esc as soon as an action is finished, and you will always
know where you are.
Knowing which mode you are in
A simple reflex: look at the bottom left of the screen. This display
depends on the showmode option, enabled by default as soon as the editor
runs in nocompatible mode, which is the case of vim started in an ordinary
terminal. With Vim on Debian 13, on Ubuntu 26.04.1 and on
AlmaLinux 10.2, with no ~/.vimrc at all, the i key makes the indicator
appear at the bottom of the screen:
-- INSERT -- 1,1 AllOn Debian 13 with vim-tiny, the showmode option is disabled: no indicator
appears, neither in insert nor in replace mode. The same goes for vim -C.
Then rely only on how the keys behave. BusyBox's vi displays a letter at the
start of its status line instead, I in insert mode and R in replace mode.
If you want the indicator, type :set showmode: it stays displayed until the
editor closes.
The absence of any indication is information too: it signals command mode. That is the row to remember in the table; the other three are recognisable at a glance.
| What you see | Active mode |
|---|---|
-- INSERT -- | Insert mode |
-- REPLACE -- | Replace mode |
| Nothing special | Command mode |
: followed by text | Ex mode |
The best way to anchor this reading is to make the round trip yourself.
Open vi /tmp/test-vi.txt: nothing shows at the bottom of the screen, you are
in command mode. Press i, and -- INSERT -- appears (if your vi displays it); type a few
letters, then Esc, and the indicator disappears. Type :, the cursor goes down to the
last line of the screen, and Esc brings you back to command mode. Five round
trips are usually enough for the reflex to set in, and for you to stop
guessing your mode.
Which keys start insert mode?
You know i to switch to insert mode, but vi offers several entry points
depending on where you want to start writing. Each one saves you time in a
precise situation.
| Key | Action | Typical situation |
|---|---|---|
i | Inserts before the cursor | General case, fixing the middle of a word |
a | Inserts after the cursor | Adding text right after a word |
I | Inserts at the start of the line | Adding a # comment in front of a line |
A | Inserts at the end of the line | Completing an existing line |
o | Opens a new line below | Adding a directive to a config file |
O | Opens a new line above | Inserting a line above the current one |
Let's take an example: you are editing /etc/hosts and the cursor is on the
line 127.0.0.1 localhost. Here is what each key does:
i→ the cursor blinks before the1of127: you write before ita→ the cursor moves after the1of127: you write after itA→ the cursor jumps to the end oflocalhost: you can add an aliaso→ an empty line appears below: you can add an entry
To feel the difference between these keys, open /tmp/test-vi.txt, put the
cursor in the middle of a word, then try in turn a followed by text and
Esc, A followed by text and Esc, and finally o followed by a whole line
and Esc. The most instructive comparison remains the one between i and
a on the same character: one character apart at the start, and all the
difference between fixing a word and completing it.
How do you move around a file?
With vi, there is no mouse. Everything is driven from the keyboard. At first, it is confusing. But once the commands are in muscle memory, it is much faster than a click.
Moving character by character
The four basic keys sit under your right hand. This layout comes from the
ADM-3A terminal that Bill Joy used: its h, j, k and l keys had
arrows printed on them. Above all, remember that a count can precede any of
them: 10j moves down ten lines at once, 5l moves forward five characters.
This numeric prefix works with almost every vi command, and it is what makes
the editor fast.
↑ k← h l → j ↓| Key | Direction | How to remember it |
|---|---|---|
h | Left ← | The leftmost key of the group |
j | Down ↓ | The j "goes down" below the baseline |
k | Up ↑ | The k "goes up" (think of a kick upwards) |
l | Right → | The rightmost key of the group |
With Vim on Debian 13, on Ubuntu 26.04.1 and on
AlmaLinux 10.2,
the arrow keys also work in insert mode: the up arrow, typed before a Z,
moves the cursor and leaves no stray letter in the file. Nobody will blame you
for using them at first. The benefit of h, j, k and l lies elsewhere:
they keep your hands on the home row, without reaching for the arrow pad. On
vim -C, which takes over the settings of vi, however, the arrow keys do not
work from insert mode: their sequence starts with the Esc key, which the
editor then no longer recognises as an arrow (esckeys option). That is the
case where hjkl stops being a purist's preference.
The same problem affects the vi of a standard Debian 13 installation, that is
vim-tiny called under the name vi in compatible mode. You open a file, you
switch to insert mode with i, you press the up arrow, then you type Z: the
cursor does not move and a letter appears in the file. On a three-line file
un, deux, trois (cursor on trois, up arrow then Z), the result
contains a line AZ opened above trois. With the left arrow, the line
becomes DZ. The arrow sends the sequence Esc, O, A (or D for left):
Esc leaves insert mode, O opens a line above, and the final letter is typed
as text. Started under the name vim.tiny, the same program is no longer in
compatible mode, and the up arrow does move the cursor.
The workaround takes two moves: leave insert mode with Esc and move with h,
j, k and l, or install the full package with sudo apt install vim.
Moving by words
To go faster than character by character, vi lets you jump from word to word. The example column shows each jump on a real nginx directive:
| Key | Action | Example on server_name localhost; |
|---|---|---|
w | Next word (start) | Jumps from server_name to localhost |
e | End of the current word | Jumps to the e of server_name |
b | Previous word (start) | Goes back from localhost to server_name |
Adding upper case (W, E, B) jumps between words separated by
spaces only, which is useful in scripts.
Moving within a line
The trap in this table is the difference between 0 and ^. The zero
goes back to column 1, so before the indentation; the caret stops at the
first non-blank character. On an indented YAML file or nginx.conf, ^ is
almost always the one you want. Remember 0 and $ too: they come back
further on as deletion ranges (d0, d$) and as anchors in searches.
| Key | Action |
|---|---|
0 (zero) | Start of the line |
^ | First non-blank character (useful for indented files) |
$ | End of the line |
Jumping to a given line
When systemctl status or nginx -t answers "error on line 42", you want
to go straight there, without counting lines. Three commands cover this need,
and the first is the most direct in troubleshooting.
| Command | Action |
|---|---|
:42 | Go to line 42 |
gg | Go to the first line of the file (1G in historical vi) |
G | Go to the last line of the file |
With Vim on Debian 13, on Ubuntu 26.04.1 and on
AlmaLinux 10.2,
gg, G and :qa! work: G
followed by i, a letter and Esc writes on the last line, gg takes you
back to the first one, and :qa! exits without writing anything.
Two variants are worth knowing. 42G does the same as :42 without going
through Ex mode, and G preceded by a number therefore follows the numeric
prefix logic seen above. Enable :set number (see the section on options)
to check at a glance that you are on the line the error message mentions.
Moving within the screen
These commands reason in terms of the displayed window, not the file: H
puts the cursor on the first visible line, not on the first line of the
file. The distinction becomes obvious in the middle of a 10,000-line log,
where H only moves a few lines while gg goes all the way up. Ctrl+f and
Ctrl+b scroll a whole screen and let you go through a long
configuration file quickly without changing it.
| Key | Action |
|---|---|
H | Top of the visible screen (High) |
M | Middle of the screen (Middle) |
L | Bottom of the screen (Low) |
Ctrl+f | Next page (forward) |
Ctrl+b | Previous page (backward) |
A real file is better than a test file for this exercise. Open
vi /etc/passwd, present on every Linux system and safe since you will not
write anything to it: move down five lines with j, jump to the end with G,
go back up with gg, go to line 10 with :10, then walk through a line word
by word with w and b. Exit with :q, without an exclamation mark. If vi
refuses to close, the file was changed without you meaning to: :q! settles
it without writing anything to disk.
Placing marks (bookmarks)
When you work on a long file, you can set bookmarks to come back quickly to a position. Two keys are enough, one to place and one to return:
ma: places a mark namedaat the cursor position'a: goes back to the line markeda
Marks go from a to z, that is 26 bookmarks per file. They
disappear when the editor closes, unless Vim keeps them in its viminfo file.
A useful nuance on long
lines: the single quote 'a puts the cursor on the first non-blank
character of the marked line, whereas the backtick followed by the same
letter restores the exact position, column included.
How do you delete text?
In command mode, vi offers deletion commands that spare you from selecting text laboriously with the mouse. Each command follows a simple logic: d + range (d for delete).
Common deletions
The first two rows of the table (x and X) act on a single character
and expect no range. The following ones all follow the d + range
pattern, where the range is exactly a movement command already seen: w,
$, 0. This regularity saves you from learning a list by heart: any new
movement command automatically becomes a deletion range. One detail to know:
dw deletes up to the start of the next word, so it also takes the space
between the two words. On server_name localhost;, a dw at the very start
leaves localhost; stuck to the margin.
| Command | What it deletes | When to use it |
|---|---|---|
x | The character under the cursor | Fix a typo |
X | The character before the cursor | Delete backwards (like Backspace) |
dw | From the cursor to the next word | Delete a word |
dd | The whole line | Delete a configuration line |
d$ | From the cursor to the end of the line | Delete the end of a line |
d0 | From the cursor to the start of the line | Delete the start of a line |
Delete several lines
You can combine a number with dd to delete a whole block:
3ddDeletes 3 lines starting from the current line. Very handy to delete a block of configuration.
Let's take an example: you are editing an nginx.conf file and want to delete a
5-line location block. Put the cursor on the first line of the block, then
type 5dd.
A point to know before going further: in vi, deleting is cutting.
Everything that d and x erase goes into a register in memory and can
be pasted back with p. A mistaken deletion can therefore be recovered in two
ways, u to undo or p to paste the text elsewhere. The corollary is less
pleasant: a dd overwrites what you had just copied with yy, since both
commands use the same register by default.
How do you change text?
Beyond deletion, vi offers commands to replace and change text without leaving command mode.
Replace one character
The r command is the shortest way to fix an isolated typo: it costs
two keystrokes and leaves you in command mode, with no Esc to go back. It is
exactly what you need on a configuration file where a single digit or letter
is wrong.
rfollowed by a character: replaces the character under the cursor without entering insert mode.
For example, the cursor is on the a of Poat 22. Type r then r →
result: Port 22. Fast, precise, no change of mode.
Replace several characters
When the fix covers a run of characters of the same length, a subnet mask
or a port number for example, replace mode saves you from deleting then
rewriting. When the indicator is displayed, the visual cue is -- REPLACE -- at the
bottom of the screen, not to be confused with -- INSERT --: in replace mode, your typing
overwrites the existing text instead of pushing it along. It is the mode
beginners fall into by pressing Insert by mistake.
R: enables replace mode. Each character you type overwrites the one under the cursor. PressEscto go back to command mode.
Change a word or a line
The c command (change) combines deletion and insertion in a single
action:
| Command | Action |
|---|---|
cw | Deletes the word and switches to insert mode |
cc | Deletes the line and switches to insert mode |
c$ | Deletes up to the end of the line and switches to insert mode |
Here is an example in an sshd_config file: the cursor is on the word
yes of the line PermitRootLogin yes. Type cw, then no, then Esc.
Result: PermitRootLogin no.
Undo and repeat
These three keys are the safety net that makes learning vi risk-free: as long
as you have not typed :w, nothing is written to disk and :q! puts the
file back in its original state. The . command deserves special
attention: it replays the last change, not the last movement. Chaining n
then . therefore lets you fix occurrence by occurrence without retyping the
command.
| Command | Action |
|---|---|
u | Undoes the last action (like Ctrl+Z) |
U | Undoes all changes on the current line |
. | Repeats the last command |
The behaviour of u differs with the program that hides behind vi, and the
difference is significant. With Vim (vim package on Debian 13 and Ubuntu 26.04.1,
vim-minimal on AlmaLinux 10.2), u goes back up the history, one press after the other. On the
text abcdef, two x give cdef; one u gives bcdef, a second u gives
abcdef, and a third u changes nothing more.
With vim-tiny on Debian 13, which imitates the historical vi, u only undoes
the last action, and a second u redoes what the first one had just
undone: it is a toggle, not a history. On the same text, x x u u gives
cdef, whereas Vim gives abcdef. The undolevels=1000 option is displayed
under vi all the same, but it changes nothing for u in compatible mode. To
know what you have, type readlink -f "$(command -v vi)", or run the test:
change a line, press u twice, and see whether the change comes back.
The vim guide details Vim's undo.
Chain these four moves on your test file to fix them in memory. On a
character, r followed by another letter replaces it. On a word, cw then a
new word then Esc changes it entirely. u brings back the original word.
Finally, . replays the last change where the cursor is: it is this last key,
apparently harmless, that changes the pace of work in vi, because it turns a
fix into a repeatable move.
How do you copy, cut and paste?
In vi, these operations have different names, taken from Unix jargon. The
vocabulary matters because it explains the letters of the commands: y comes
from yank, p from put. They all share the same storage location, the
unnamed register, which explains why a deletion overwrites what you had
just copied.
| Usual operation | Name in vi | Command |
|---|---|---|
| Copy | Yank | y |
| Cut | Delete | d |
| Paste | Put | p |
Copy (yank)
Copying follows the pattern already met with d: verb + range. Doubling
the letter (yy) designates the whole line, like dd for deletion. Copying
does not change the file and does not move the cursor. On a single line, it
shows no message, so you get no visual confirmation; from three lines on, a
3 lines yanked message is displayed at the bottom of the screen. This message
is in English; on a system set to French, it may be translated. The threshold
comes from the report option, which is 2: yy and 2yy display nothing more
than the file name, 3yy displays the message. This behaviour is the same with Vim on Debian 13, on Ubuntu 26.04.1 and on AlmaLinux 10.2, with or
without set nocompatible.
| Command | What it copies |
|---|---|
yy | The whole line |
yw | A word |
y$ | From the cursor to the end of the line |
3yy | 3 lines starting from the cursor |
Cut (delete)
As seen in the deletion section, every d command cuts the text: it
stays in memory to be pasted:
| Command | What it cuts |
|---|---|
dd | The whole line |
dw | A word |
d3w | Three words |
Paste (put)
The behaviour of p depends on what was copied, and it is a frequent
source of surprise. If the copy covered whole lines (yy, dd), pasting
inserts new lines below the current line. If it covered characters (yw,
y$), the text is inserted inside the line, just after the cursor. The
contents of the register are not consumed: you can press p several times in a
row to duplicate a block.
| Command | Action |
|---|---|
p | Pastes after the cursor (or below the line if you copied a whole line) |
P | Pastes before the cursor (or above the line) |
Practical example: move a line
Suppose you are editing an nginx.conf file and a directive is in the wrong
place. To move line 5 below the current line 10, four steps are enough:
-
Go to line 5: type
:5thenEnter -
Cut the line: type
dd -
Go to the destination: type
:9(line 9 is the former line 10 after the cut) -
Paste below: type
p
Named registers
By default, each copy or cut replaces what was in memory. If you need to store
several pieces of text, use the named registers (from a to z):
"ayy → copies the line into register a"byy → copies the line into register b"ap → pastes the contents of register a"bp → pastes the contents of register bThe double quote " is a prefix: it announces that the next letter designates
a register, not a command. You thus have 26 independent slots, a to z,
on top of the unnamed register used by default. A useful detail when sorting a
configuration: naming the register in upper case ("Ayy) appends the line
to what is already stored in a instead of overwriting it, which lets you
gather scattered lines before pasting them as one block.
How do you search and replace?
When you work on a 200-line configuration file, looking for a parameter by eye is inefficient. Vi has powerful search commands and a replacement system comparable to the "find and replace" of graphical editors.
Search for a word
The search starts from command mode with / to go down the file and ? to
go up. The character you type shows at the bottom of the screen, followed by
the pattern you enter, and the search starts when you confirm with
Enter. The cursor then moves to the first match found in the chosen
direction, starting from the current position and not from the start of the
file.
/patternthenEnter: searches down the file?patternthenEnter: searches up
To find the occurrences of Port in sshd_config, type:
/PortVi jumps to the first occurrence found. If the pattern is absent, the editor shows an error that repeats the pattern searched and leaves the cursor where it was, without changing anything:
E486: Pattern not found: zzzzThis message is the one of an English locale: on a system set to French, it may be translated.
Moving between results
Once the search has started, you no longer need to retype the pattern. Two
points to keep in mind. First, n and N are relative to the initial
direction: after a ?pattern, it is n that goes up the file. Second, the
search wraps around at the end of the file thanks to the wrapscan
option, enabled by default: vi starts again from the top of the file and shows
search hit BOTTOM, continuing at TOP (English locale text). Seeing this
message means you have gone round all the occurrences.
n: next occurrence (same direction)N: previous occurrence (opposite direction)
Searching with simple patterns
Vi interprets the search pattern as a regular expression, not as literal
text. This has an immediate practical consequence: in a
search for version.1, the . is not a dot but a wildcard, and vi also finds
version-1 or version21. To search for a special
character as is, precede it with a backslash: /version\.1 only finds
version.1.
The patterns in the table cover most needs in administration. The
last two, ^ and $, are the most rewarding: they anchor the search at the
start or end of the line and avoid false positives in the middle of the text.
| Pattern | Meaning | Example |
|---|---|---|
. | Any character | /s.rv finds serv and surv |
* | Zero or more of the previous character | /ab*c finds ac, abc, abbc |
^ | Start of line | /^# finds the commented lines |
$ | End of line | /;$ finds the lines ending with ; |
Replace text
Substitution uses the :s command in Ex mode. Its syntax always reads the
same way: a range of lines, then s, then the pattern to find, then the
replacement text, then flags. What changes from one tab to the next below
is only the range and the flags. Without a range, the substitution only
touches the current line; without the g flag, it only replaces the first
occurrence on each line. Forgetting the g explains most substitutions "that
did not replace everything".
Replace the first occurrence on the line:
:s/old/new/Replace every occurrence on the line:
:s/old/new/gReplace every occurrence in the file:
:%s/old/new/gThe % means "every line of the file".
Ask for confirmation at each replacement:
:%s/old/new/gcVi shows each occurrence and asks you y (yes), n (no)
or a (all the remaining ones). The prompt is:
replace with X (y/n/a/q/l/^E/^Y)?On a three-line file, y then n then a gave X1, line2, X3: y
replaces the occurrence displayed, n skips it, a replaces all the remaining
occurrences without asking again.
To replace port 8080 with 443 everywhere in an Apache file,
type:
:%s/8080/443/gPractise on /tmp/test-vi.txt, where a failed substitution costs nothing:
search for a word with /word and go through the occurrences with n,
replace it on the current line with :s/old/new/, then in the whole file with
:%s/old/new/g. Then compare the number of substitutions announced at the
bottom of the screen with what you expected: it is the simplest check of a
substitution, and it immediately reveals a forgotten g. The summary is in
English and only appears beyond two substitutions (same report threshold as
for copying):
3 substitutions on 3 linesWith a single substitution, no summary is displayed.
How do you customise vi?
Vi is minimalist, but a few settings make it more comfortable. These
options are enabled in Ex mode (:) and stay active for the session.
Useful options
Read the table in pairs: each boolean option is turned off by prefixing its
name with no. On a server, two of them help straight away.
:set number shows the line numbers, essential when a service refuses
to start and points to "error on line 87". :set autoindent keeps the
indentation of the previous line, which avoids breaking a YAML file
when you add a key. A known downside of autoindent: pasting an already
indented block with the mouse produces a staircase, because the pasted
indentation adds to the generated one. Disable the option with
:set noautoindent before a large paste.
| Command | What it does |
|---|---|
:set number | Shows the line numbers |
:set nonumber | Hides the line numbers |
:set ignorecase | Case-insensitive search |
:set noignorecase | Case-sensitive search |
:set autoindent | Keeps the indentation on a new line |
:set tabstop=4 | Sets the tab width to 4 spaces |
:set showmode | Shows the active mode at the bottom (INSERT, REPLACE) |
To enable several options in a single command:
:set number autoindent tabstop=4To see every active option, type :set with no argument.
These settings do not survive closing the editor. To keep them, vi reads a
~/.exrc file, or the EXINIT variable, both defined by POSIX. The
vi of Vim (vim package on Debian 13 and Ubuntu 26.04.1, vim-minimal on
AlmaLinux 10.2) reads
them: with set number in ~/.exrc, or with EXINIT='set number',
:set number? answers number. Two limits apply. Vim only reads ~/.exrc if
no ~/.vimrc exists, and it does not read by default an .exrc placed in the
current directory (:set number? then answers nonumber).
Both mechanisms accept ex commands, including set. On the rescue machine you
land on, they do not exist: count on typing :set number again at each
opening. It is one of the reasons to move to vim as soon as the machine is no longer a rescue system, its .vimrc
file making these same options permanent along with much more.
Troubleshooting: beginner mistakes
Almost every block in vi has the same origin: the active mode is not the
one you think. Before looking further, press Esc and look at the bottom
line. Two symptoms are exceptions, the codes E45 and E212: they come from
the permissions on the file or on its folder, not from the mode, and are
not solved the same way. So read the "Cause" column before the "Fix" column: it
tells you whether it is a mode or a permissions problem.
| Problem | Cause | Fix |
|---|---|---|
| I type text but nothing shows | You are in command mode | Press i to switch to insert mode |
| Commands run when I type | You are in command mode while you want to write | Press i, a or o |
| I cannot exit vi | You have unsaved changes | Type :wq (save and exit) or :q! (exit without saving) |
Vi shows "/etc/new-file.txt" E212: Can't open file for writing | The file does not exist and you cannot create it: the folder is not writable | Open the file with sudo vi file, or choose a folder where you can write |
| The text I type replaces characters | You are in replace mode (R) | Press Esc to go back to command mode |
:wq shows E45: 'readonly' option is set (add ! to override) | The file exists but you opened it read-only: it belongs to another user without write permission for you, or you started vi -R | Reopen with sudo vi file; :w! only forces the write if the system allows it, for example if you own the file or you are root |
An arrow key, typed in insert mode, does not move the cursor and opens a line containing a letter (A or D) | Your vi is vim-tiny in compatible mode (Debian 13, standard installation): it reads the arrow as separate keys | Press Esc, delete the extra line with dd, move with h, j, k, l, or install the full package with sudo apt install vim |
| I made a wrong move | You changed the file by mistake | Type u to undo (only once with vim-tiny: a second u redoes), or :q! to discard everything |
What are the limits of vi, and what replaces it?
Vi is reliable and universal, but it has limits inherited from its design
in 1976. vim fills each of them, which is why it is the one you usually
get when you type vi:
| What vi does not do | The vim alternative |
|---|---|
| No syntax highlighting | :syntax on |
Undo limited to 1 level, u as a toggle (historical vi, vim-tiny on Debian 13) | Undo over 1000 levels with u (vim package) |
| No text completion | Ctrl+n / Ctrl+p |
| No plugins | Many plugins available |
A minimal configuration file (~/.exrc) | .vimrc for rich, permanent customisation |
| No intuitive multi-file editing | Tabs, splits, buffers |
How do you know whether you are using vi or vim?
It depends on the system. On the Ubuntu 26.04 images measured and on
AlmaLinux 10, vi starts vim (Vi IMproved). On Debian 13, it starts
vim-tiny after an installation with the standard system utilities, and full
Vim if the vim package is installed. The "Prerequisites" section details the
three cases. To know what you have:
readlink -f "$(command -v vi)"The result /usr/bin/vim.tiny designates vim-tiny, which behaves like the
original vi. To switch to Vim on Debian 13, install the vim package. With
vi --version | head -1, the answer VIM - Vi IMproved indicates a Vim. A
minimal image that only ships BusyBox answers differently. When vi is already
a Vim, you can go straight to the
vim guide to discover the advanced features.
Key points
- vi is almost everywhere: you find it on almost every Unix/Linux system, rescue mode and Alpine included.
- The basic cycle:
i(insert) → text →Esc(command mode) →:wq(save and exit). Escalways brings you back to command mode: it is the only key whose effect is the same whatever the active mode.- Your
viis not necessarily Vim:readlink -f "$(command -v vi)"tells you. On Debian 13,vim-tinydoes not display-- INSERT --,uworks as a toggle there and the arrow keys do not move the cursor in insert mode; thevimpackage fixes all three. - The commands follow a logic:
d+ range to delete,y+ range to copy,c+ range to change. - Searching is fast:
/patternto search,nfor the next occurrence. - vi is only a start: once the basics are learnt, move on to vim for syntax highlighting, plugins and permanent customisation.
Knowledge check
Check that the essentials of this guide stuck. The questions cover only what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Use the Linux shell efficiently
A new full quiz with random questions
Work again only on the questions you missed
FAQ: frequently asked questions
These questions sum up what vi beginners ask most often: how to get out, how the modes work, and when to move on to vim.
Definition
vi (short for visual) is a command-line text editor created in 1976 by Bill Joy. It is present on almost every Unix and Linux system.Why learn it?
vi remains available even on minimal systems:- Server in rescue mode (no other editor installed)
- Minimal container based on Alpine (BusyBox's vi)
- SSH connection to a network device or an embedded system
- Emergency troubleshooting on a system without a graphical interface
Comparison with other editors
| Characteristic | vi | nano | VS Code |
|---|---|---|---|
| Availability | Almost everywhere | Often installed | Graphical desktop only |
| Weight | Very light | Light | Larger |
| Learning curve | Steep at first | Easy | Intuitive |
| Features | Basic | Basic | Very rich |
| Main use | Server troubleshooting | Simple editing | Development |
The basic cycle
The fundamental cycle with vi comes down to 4 steps:- Open:
vi file_name - Write: press
ito switch to insert mode, then type the text - Go back to command mode: press
Esc - Save and exit: type
:wqthenEnter
Exit commands
| Command | Action |
|---|---|
:wq |
Save and exit |
:q! |
Exit without saving |
:w |
Save without exiting |
:q |
Exit (fails if there are unsaved changes) |
ZZ |
Shortcut to save and exit (no :) |
:w new_name |
Save under another name |
The three modes
| Mode | How to enter it | Role | How to leave it |
|---|---|---|---|
| Command | Esc (or on opening) |
Move, delete, copy, paste | Type i, a, o or : |
| Insert | i, a, o, O |
Write text | Press Esc |
| Ex | : from command mode |
Long commands (:w, :q, :%s/…) |
Enter or Esc |
Recognising the active mode
| Indicator at the bottom of the screen | Mode |
|---|---|
-- INSERT -- |
Insert mode (absent with vim-tiny on Debian 13) |
-- REPLACE -- |
Replace mode |
: followed by text |
Ex mode |
| Nothing special | Command mode |
vim-tiny, which does not display -- INSERT --. Type :set showmode to display it, or install the vim package.Six ways into insert mode
| Key | Inserts where | Typical situation |
|---|---|---|
i |
Before the cursor | Fixing the middle of a word |
a |
After the cursor | Adding text right after |
I |
At the start of the line | Adding a # in front of a line |
A |
At the end of the line | Completing an existing line |
o |
New line below | Adding a directive to a config file |
O |
New line above | Inserting a line above |
Esc to go back to command mode.Moving character by character
| Key | Direction |
|---|---|
h |
Left ← |
j |
Down ↓ |
k |
Up ↑ |
l |
Right → |
vim package, the arrow keys also work in insert mode. With vim-tiny, installed by default on Debian 13, an arrow typed in insert mode opens a line containing a letter: press Esc and use h, j, k, l.Moving by words, lines and screens
| Command | Action |
|---|---|
w / b / e |
Next word / previous word / end of word |
0 / ^ / $ |
Start of line / first non-blank / end of line |
gg / G |
First / last line of the file |
:42 |
Go to line 42 |
H / M / L |
Top / middle / bottom of the screen |
Ctrl+f / Ctrl+b |
Next / previous page |
Marks
ma places a mark named a, and 'a goes back to that line. Marks go from a to z.Deletion commands
Every deletion command is used in command mode and follows thed + range logic:| Command | What it deletes |
|---|---|
x |
Character under the cursor |
X |
Character before the cursor |
dw |
From the cursor to the next word |
dd |
The whole line |
d$ |
From the cursor to the end of the line |
d0 |
From the cursor to the start of the line |
3dd |
3 lines starting from the current one |
Deleting is cutting
Any text deleted withd or x is stored in memory. You can paste it back with p (after the cursor) or P (before it).Quick replacement
| Command | Action |
|---|---|
r + character |
Replaces the character under the cursor without changing mode |
R |
Enables replace mode (each keystroke overwrites a character) |
cw |
Deletes the word and switches to insert mode |
cc |
Deletes the line and switches to insert mode |
c$ |
Deletes up to the end of the line and switches to insert mode |
Undo and repeat
| Command | Action |
|---|---|
u |
Undoes the last action (with the vim package, each press goes one step further back in the history) |
U |
Undoes every change on the current line |
. |
Repeats the last change |
vim package on Debian 13 and Ubuntu 26.04, vim-minimal on AlmaLinux 10), repeated u goes back up the history (up to 1000 levels by default). With vim-tiny, installed by default on Debian 13 with the standard system utilities, u works as a toggle like in historical vi: a first u undoes, a second one redoes (x x u u on abcdef gives cdef). See vim for Vim's undo.The vi vocabulary
| Operation | Name in vi | Command |
|---|---|---|
| Copy | Yank | y (yy for a line, 3yy for 3 lines; the 3 lines yanked message appears from three lines on) |
| Cut | Delete | d (dd for a line) |
| Paste | Put | p after, P before |
Named registers
To keep several pieces of text, use registersa to z:"ayy → copies the line into register a
"ap → pastes the contents of register a
Naming the register in upper case ("Ayy) appends to it instead of overwriting it.Simple search
| Command | Action |
|---|---|
/pattern |
Searches down the file |
?pattern |
Searches up |
n |
Next occurrence (same direction) |
N |
Previous occurrence (opposite direction) |
Basic regular expressions
| Pattern | Meaning | Example |
|---|---|---|
. |
Any character | /s.rv finds serv and surv |
^ |
Start of line | /^# finds the commented lines |
$ |
End of line | /;$ finds the lines ending with ; |
/version\.1.Substitution syntax
| Command | Scope |
|---|---|
:s/old/new/ |
First occurrence on the current line |
:s/old/new/g |
Every occurrence on the current line |
:%s/old/new/g |
Every occurrence in the whole file |
:%s/old/new/gc |
Whole file with confirmation at each replacement |
% means every line of the file. With the c flag, vi asks y (yes), n (no) or a (all the remaining ones).Example
Replace port 8080 with 443 in an Apache file::%s/8080/443/g
Frequent problems
| Problem | Cause | Fix |
|---|---|---|
| I type text but nothing shows | You are in command mode | Press i |
| I cannot exit | Unsaved changes | :wq or :q! |
E212: Can't open file for writing |
The file does not exist and the folder is not writable | sudo vi file or another folder |
| The text replaces characters | Replace mode active (R) |
Press Esc |
E45: 'readonly' option is set (add ! to override) |
Existing file opened read-only (permissions or vi -R) |
sudo vi file; :w! only if the system allows it, for example if you own the file or are root |
| Wrong move | Changed by mistake | u to undo (only once with vim-tiny, a second u redoes) or :q! to discard |
The golden rule
When you are lost in vi, pressEsc two or three times. It always brings you back to command mode. Then type :q! to exit without saving.Comparison
| Feature | vi | vim |
|---|---|---|
| Syntax highlighting | No | Yes (:syntax on) |
| Undo | 1 level (toggle) in historical vi and vim-tiny |
1000 levels by default (vim package) |
| Text completion | No | Ctrl+n / Ctrl+p |
| Plugins | No | Many plugins available |
| Persistent configuration | ~/.exrc, ex commands |
Rich .vimrc file |
| Multi-file editing | Basic | Tabs, splits, buffers |
Check what you are using
On the Ubuntu 26.04 images measured and on AlmaLinux 10,vi starts vim. On Debian 13, vim-tiny has priority important and vim has priority optional: a standard installation provides vim-tiny, which reads /etc/vim/vimrc.tiny (set compatible). Consequences: no -- INSERT -- indicator, u as a toggle, and the arrow keys typed in insert mode do not move the cursor (they open a line with a letter). To know what you have:readlink -f "$(command -v vi)"
The result /usr/bin/vim.tiny designates vim-tiny. To get the behaviour of vim, install the vim package (sudo apt install vim).Useful options
| Command | Effect |
|---|---|
:set number |
Shows line numbers |
:set ignorecase |
Case-insensitive search |
:set autoindent |
Automatic indentation |
:set tabstop=4 |
Tab width of 4 spaces |
:set showmode |
Shows the active mode at the bottom |
:set number autoindent tabstop=4. To see the active options, type :set with no argument.Making them permanent
Vi reads a~/.exrc file or the EXINIT variable, defined by POSIX, which hold ex commands, including set (an .exrc in the current directory is not read by default). On the rescue machine where you use vi, that file is usually absent, so plan on retyping your settings. For rich, permanent customisation, move to vim and its .vimrc file.