Menu

GNU and Unix Commands

Step 8 of 8 LPIC-1 103.8weight 3

Basic file editing

“Survive and thrive in vi: modes, moving around, inserting, deleting, copying, searching, saving, plus nano, Emacs and the EDITOR variable.”

View .md

Sooner or later you’ll edit a config file on a server with no graphical desktop: over SSH, in a container, or in a rescue shell after a bad boot. The one editor you can count on in all of those places is vi. It’s required by the POSIX standard, so it’s on nearly every Unix-like system, and commands like crontab -e and visudo drop you into it by default.

vi has a reputation for being hard, mostly because it doesn’t behave like other editors: typing letters doesn’t insert them until you ask it to. Once you understand its modes, a small set of keys covers everything the exam asks.

On today’s systems, vi is usually vim (“vi improved”) in a small build: vim-tiny on Debian and Ubuntu, vim-minimal on RHEL and Fedora. Install the full vim package for syntax colors and the 30-minute interactive lesson vimtutor.

Opening a file#

bash
vi notes.txt           # open (or create) a file
vi +25 notes.txt       # open with the cursor on line 25
vi + notes.txt         # open at the last line
vi +/Port sshd_config  # open at the first line matching "Port"
vi -R notes.txt        # read-only (same as: view notes.txt)

Minimal containers don’t include an editor at all. Use apt install vim (Debian/Ubuntu) or dnf install vim-enhanced (RHEL/Fedora) to practice.

The modes#

vi always is in one of these modes:

ModeWhat keys doHow to get there
Normal (command) modeMove, delete, copy, paste. Letters are commandsYou start here. Esc always brings you back
Insert modeType text, like any editori, a, o and friends (see below)
Command-line (ex) modeRun a : command: save, quit, replaceType : in normal mode, finish with Enter
Visual mode (vim)Select text with the movement keysv (characters), V (lines), Ctrl+V (block)

The golden rule: when in doubt, press Esc. You’re back in normal mode and can decide what to do next. vim shows -- INSERT -- at the bottom while you’re in insert mode.

Moving around#

In normal mode:

KeyMoves
h j k lLeft, down, up, right (arrow keys work too)
w / b / eNext word / back a word / end of the word
0 / ^ / $Start of the line / first non-blank character / end of the line
gg / GFirst line / last line
25G or :25Line 25
Ctrl+F / Ctrl+BOne page forward / back

h j k l sit under your right hand, so you never leave the home row. Put a number before most commands to repeat them: 5j moves five lines down.

Inserting text#

Each of these switches to insert mode in a different place. Press Esc when you’re done typing:

KeyStarts inserting
iBefore the cursor
aAfter the cursor (append)
IAt the start of the line
AAt the end of the line
oOn a new line below
OOn a new line above

A is the one you’ll love for config files: jump to the end of the line and add something.

Deleting, copying and pasting#

vi uses d for delete, y for yank (copy) and p for put (paste). Deleted text isn’t lost: it goes into a buffer (vi calls it a register), so delete-then-paste is how you cut and paste.

KeyAction
xDelete the character under the cursor
ddDelete (cut) the whole line
3ddDelete 3 lines
dwDelete to the end of the word
d$ or DDelete to the end of the line
dGDelete to the end of the file
yyYank (copy) the line
3yyYank 3 lines
ywYank a word
pPut after the cursor (or below, for whole lines)
PPut before the cursor (or above)

The pattern is operator + motion: d or y followed by a movement key. dw deletes a word, d$ to the end of the line, y0 copies to the start of the line. Doubling the letter (dd, yy) means “the whole line”.

So to move a line down three lines: dd, 3j, p. To duplicate a line: yy, p.

Besides the default register, vi has named registers a to z. Put "a before a command to use one: "ayy copies the line into register a, and "ap pastes it later, while normal yy and p keep working with the default register.

Changing and undoing#

KeyAction
r + a characterReplace one character
ROverwrite mode, until Esc
cwChange a word: delete it and go to insert mode
ccChange the whole line
JJoin the next line to this one
uUndo
Ctrl+RRedo (vim)
.Repeat the last change

. is a hidden gem: change one word with cw, then move to the next one and press . to make the same change again.

Finding text#

KeyAction
/text + EnterSearch forward for text
?text + EnterSearch backward
nNext match, in the same direction
NNext match, in the opposite direction

The search text is a regular expression, so /^Port finds a line starting with “Port”.

To replace, use an ex command:

text
:s/old/new/       replace the first "old" on the current line
:s/old/new/g      every "old" on the current line
:%s/old/new/g     every "old" in the whole file (% = all lines)
:%s/old/new/gc    the same, but ask for each one
:10,20s/old/new/g only in lines 10 to 20

It’s the same s command as in sed.

Saving and quitting#

All the : commands are typed in normal mode and finished with Enter:

CommandAction
:wWrite (save)
:w newnameSave under another name
:w!Force the write, for example over a read-only file you own (or as root)
:qQuit (refuses if there are unsaved changes)
:q!Quit and throw away changes
:wq or :xSave and quit
ZZSave (if changed) and quit, like :x. No colon, no Enter
ZQQuit without saving, like :q!
:e!Throw away changes and reload the file from disk

The ! means “yes, I’m sure”: it overrides the safety check that would otherwise stop you.

A few more ex commands that are good to know:

CommandAction
:set number / :set nonumberShow / hide line numbers
:r fileRead another file in below the cursor
:!commandRun a shell command, then return to vi
:e fileOpen another file
:helpBuilt-in help (vim)

Tip

If the screen looks frozen, you may have pressed Ctrl+S, which pauses terminal output. Ctrl+Q resumes it. And if you opened a root-owned file without sudo and can’t save, :w !sudo tee % writes it through sudo (vim).

A complete edit, step by step#

Change the SSH port in a config file:

  1. sudo vi /etc/ssh/sshd_config
  2. /^#Port + Enter: jump to the line #Port 22, with the cursor on the #.
  3. x: delete the #. The cursor is now on Port.
  4. w to jump to 22, then cw, type 2222, press Esc.
  5. :wq + Enter.

A handful of keystrokes and no mouse. With practice it takes a few seconds.

Other editors: nano, Emacs and vim#

You only need awareness of these for LPIC-1:

  • nano is the friendly one. You type straight away, and the shortcuts are listed at the bottom of the screen (^ means Ctrl): Ctrl+O saves, Ctrl+X exits, Ctrl+W searches, Ctrl+K cuts a line and Ctrl+U pastes it. It’s the default editor on Debian, Ubuntu and Fedora.
  • Emacs is a big, extensible editor from the GNU project. It has no modes like vi; commands use Ctrl and Alt (called Meta) combinations: Ctrl+X Ctrl+S saves, Ctrl+X Ctrl+C quits, Ctrl+X Ctrl+F opens a file.
  • vim is the improved vi you’ve been using: undo history, syntax colors, visual mode, split windows and plugins. Its settings live in ~/.vimrc.

Choosing the standard editor: EDITOR#

Programs that open an editor for you, like crontab -e, visudo, git commit or less (press v), check two environment variables:

  • VISUAL: the full-screen editor to use. Checked first.
  • EDITOR: the editor to use. Checked if VISUAL isn’t set.

If neither is set, they fall back to a default, often vi. Set your choice in ~/.bashrc (or ~/.bash_profile) so every new shell has it:

~/.bashrcbash
export EDITOR=vim
export VISUAL=vim

Or just for one command:

bash
EDITOR=nano crontab -e

Debian and Ubuntu add a system-wide layer: /usr/bin/editor is a link managed by the alternatives system, and select-editor stores a per-user choice in ~/.selected_editor:

bash
sudo update-alternatives --config editor
select-editor
text
There are 3 choices for the alternative editor (providing /usr/bin/editor).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /bin/nano            40        auto mode
  1            /bin/nano            40        manual mode
  2            /usr/bin/vim.basic   30        manual mode
  3            /usr/bin/vim.tiny    15        manual mode

On RHEL, Fedora and most other systems, EDITOR and VISUAL are all you need. Fedora sets EDITOR=nano by default through a small file in /etc/profile.d/; RHEL leaves it unset, so tools fall back to vi.

Exam checklist#

  • vi starts in normal (command) mode. i, a, o (and I, A, O) enter insert mode; Esc goes back. : opens command-line (ex) mode.
  • Move with h (left), j (down), k (up), l (right). gg/G first/last line, 0/$ start/end of line, w/b by word.
  • dd deletes a line, yy copies it, p pastes after, P before. A number in front repeats: 5dd, 3yy. x deletes a character, u undoes.
  • /text searches forward, ?text backward, n repeats. :%s/old/new/g replaces in the whole file.
  • :w save, :w! force save, :q quit, :q! quit without saving, :wq, :x and ZZ save and quit.
  • vi +N file opens at line N. vi -R or view opens read-only.
  • EDITOR (and VISUAL, checked first) set the default editor for tools like crontab -e. Debian also has update-alternatives --config editor and select-editor.
  • Awareness: nano (Ctrl+O save, Ctrl+X exit), Emacs (Ctrl+X Ctrl+S save, Ctrl+X Ctrl+C quit), vim (vi improved).

Byte check

0/3

Answer these 3 questions to commit this byte to your learning path.

  1. You’ve made a mess of a file in vi and want to leave without saving. What do you type?
  2. In normal mode, which key opens a new line below the cursor and switches to insert mode?
  3. What does 3yy followed by p do?
Search posts and bytes

Optional account

Keep your progress everywhere

Everything on AminBytes is free to read, with or without an account. Sign in only if you want your commits, streak and merged topics saved, on every device.

or

We keep only your name, avatar and which bytes you finished, and you can delete it all anytime. Privacy