Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Vi on Linux: modes, essential commands and how to exit

By updated

Improve this page

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.

CharacteristicviGraphical editor (VS Code, etc.)
AvailabilityEverywhere, even without a desktopRequires a graphical environment
WeightLightMuch larger
Learning curveSteep at first, then fastIntuitive from the start
Typical useServer troubleshooting, quick editsEveryday 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:

Terminal window
which vi

The 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:

Terminal window
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.

Debian 13, vim-tiny alone, vim package removed (2:9.1.1230-2+deb13u2, measured on 2026-11-13)
/usr/bin/vim.tiny

In 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:

Terminal window
readlink -f "$(command -v vi)"
vi --version | head -2
Debian 13, vim package 2:9.1.1230-2+deb13u2 (measured on 2026-11-13)
/usr/bin/vim.basic
VIM - Vi IMproved 9.1 (2024 Jan 02, compiled Nov 04 2026 22:12:34)
Included patches: 1-948, 950-1230, 1242, 1244

On 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):

AlmaLinux 10.2 (measured on 2026-11-13)
/usr/bin/vi
VIM - Vi IMproved 9.1 (2024 Jan 02, compiled Sep 29 2026 00:00:00)
Included patches: 1-83

With 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.

  1. Open vi on a test file

    Create a temporary file to practise without risk:

    Terminal window
    vi /tmp/test-vi.txt

    Vi 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.

  2. Switch to insert mode to write

    Press the i key (as in insert). You are now in insert mode: you can type text normally. If your vi displays the modes, -- INSERT -- appears at the bottom of the screen; on Debian 13 with vim-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.
  3. Go back to command mode

    Press the Esc key. If -- INSERT -- was displayed, it disappears. You are back in command mode.

  4. Save and exit

    Type :wq then press Enter.

    • : opens Ex mode (the command line at the bottom of the screen)
    • w means write (save)
    • q means quit
  5. Check that the file was saved

    Back in the terminal, show the contents of the file:

    Terminal window
    cat /tmp/test-vi.txt

    You 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:

Demonstration GIF of the open, write, save cycle with vi

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.

SituationCommandWhat it does
Save and exit:wq then EnterWrites the file and closes vi
Exit without saving:q! then EnterDiscards the changes
Just save:w then EnterWrites the file, stays in vi
Just exit (nothing to save):q then EnterCloses vi (fails if there are unsaved changes)
Save + exit shortcutZZ (upper case, no :)Equivalent to :wq
Save under another name:w new_nameCreates 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.

ModeHow to enter itWhat it doesHow to leave it
CommandEsc (or on opening)Move, delete, copy, pasteType i, a, o or :
Inserti, a, o, OWrite textPress 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:

Last line of the screen after i (Debian 13 with vim and Ubuntu 26.04, 80 columns)
-- INSERT -- 1,1 All

On 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 seeActive mode
-- INSERT --Insert mode
-- REPLACE --Replace mode
Nothing specialCommand mode
: followed by textEx 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.

KeyActionTypical situation
iInserts before the cursorGeneral case, fixing the middle of a word
aInserts after the cursorAdding text right after a word
IInserts at the start of the lineAdding a # comment in front of a line
AInserts at the end of the lineCompleting an existing line
oOpens a new line belowAdding a directive to a config file
OOpens a new line aboveInserting 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 the 1 of 127: you write before it
  • a → the cursor moves after the 1 of 127: you write after it
  • A → the cursor jumps to the end of localhost: you can add an alias
  • o → 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
↓
KeyDirectionHow to remember it
hLeft ←The leftmost key of the group
jDown ↓The j "goes down" below the baseline
kUp ↑The k "goes up" (think of a kick upwards)
lRight →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:

KeyActionExample on server_name localhost;
wNext word (start)Jumps from server_name to localhost
eEnd of the current wordJumps to the e of server_name
bPrevious 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.

KeyAction
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.

CommandAction
:42Go to line 42
ggGo to the first line of the file (1G in historical vi)
GGo 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.

KeyAction
HTop of the visible screen (High)
MMiddle of the screen (Middle)
LBottom of the screen (Low)
Ctrl+fNext page (forward)
Ctrl+bPrevious 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 named a at the cursor position
  • 'a: goes back to the line marked a

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.

CommandWhat it deletesWhen to use it
xThe character under the cursorFix a typo
XThe character before the cursorDelete backwards (like Backspace)
dwFrom the cursor to the next wordDelete a word
ddThe whole lineDelete a configuration line
d$From the cursor to the end of the lineDelete the end of a line
d0From the cursor to the start of the lineDelete the start of a line

Delete several lines

You can combine a number with dd to delete a whole block:

3dd

Deletes 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.

  • r followed 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. Press Esc to go back to command mode.

Change a word or a line

The c command (change) combines deletion and insertion in a single action:

CommandAction
cwDeletes the word and switches to insert mode
ccDeletes 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.

CommandAction
uUndoes the last action (like Ctrl+Z)
UUndoes 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 operationName in viCommand
CopyYanky
CutDeleted
PastePutp

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.

CommandWhat it copies
yyThe whole line
ywA word
y$From the cursor to the end of the line
3yy3 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:

CommandWhat it cuts
ddThe whole line
dwA word
d3wThree 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.

CommandAction
pPastes after the cursor (or below the line if you copied a whole line)
PPastes 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:

  1. Go to line 5: type :5 then Enter

  2. Cut the line: type dd

  3. Go to the destination: type :9 (line 9 is the former line 10 after the cut)

  4. 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 b

The 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.

  • /pattern then Enter: searches down the file
  • ?pattern then Enter: searches up

To find the occurrences of Port in sshd_config, type:

/Port

Vi 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:

After /zzzz then Enter (Debian 13 with vim, Ubuntu 26.04)
E486: Pattern not found: zzzz

This 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.

PatternMeaningExample
.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/g

To replace port 8080 with 443 everywhere in an Apache file, type:

:%s/8080/443/g

Practise 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):

After :%s/line/X/g on three lines
3 substitutions on 3 lines

With 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.

CommandWhat it does
:set numberShows the line numbers
:set nonumberHides the line numbers
:set ignorecaseCase-insensitive search
:set noignorecaseCase-sensitive search
:set autoindentKeeps the indentation on a new line
:set tabstop=4Sets the tab width to 4 spaces
:set showmodeShows the active mode at the bottom (INSERT, REPLACE)

To enable several options in a single command:

:set number autoindent tabstop=4

To 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.

ProblemCauseFix
I type text but nothing showsYou are in command modePress i to switch to insert mode
Commands run when I typeYou are in command mode while you want to writePress i, a or o
I cannot exit viYou have unsaved changesType :wq (save and exit) or :q! (exit without saving)
Vi shows "/etc/new-file.txt" E212: Can't open file for writingThe file does not exist and you cannot create it: the folder is not writableOpen the file with sudo vi file, or choose a folder where you can write
The text I type replaces charactersYou 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 -RReopen 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 keysPress 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 moveYou changed the file by mistakeType 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 doThe 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 completionCtrl+n / Ctrl+p
No pluginsMany plugins available
A minimal configuration file (~/.exrc).vimrc for rich, permanent customisation
No intuitive multi-file editingTabs, 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:

Terminal window
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).
  • Esc always brings you back to command mode: it is the only key whose effect is the same whatever the active mode.
  • Your vi is not necessarily Vim: readlink -f "$(command -v vi)" tells you. On Debian 13, vim-tiny does not display -- INSERT --, u works as a toggle there and the arrow keys do not move the cursor in insert mode; the vim package fixes all three.
  • The commands follow a logic: d + range to delete, y + range to copy, c + range to change.
  • Searching is fast: /pattern to search, n for 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

6 questions
6 min
70% to pass

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

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.