# Basic file editing

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

Source: https://aminbytes.dev/bytes/gnu-and-unix-commands/file-editing/


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.

 (Side note: 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:

| Mode | What keys do | How to get there |
| --- | --- | --- |
| **Normal** (command) mode | Move, delete, copy, paste. Letters are commands | You start here. `Esc` always brings you back |
| **Insert** mode | Type text, like any editor | `i`, `a`, `o` and friends (see below) |
| **Command-line** (ex) mode | Run a `:` command: save, quit, replace | Type `:` in normal mode, finish with `Enter` |
| **Visual** mode (vim) | Select text with the movement keys | `v` (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:

| Key | Moves |
| --- | --- |
| `h` `j` `k` `l` | Left, down, up, right (arrow keys work too) |
| `w` / `b` / `e` | Next word / back a word / end of the word |
| `0` / `^` / `$` | Start of the line / first non-blank character / end of the line |
| `gg` / `G` | First line / last line |
| `25G` or `:25` | Line 25 |
| `Ctrl+F` / `Ctrl+B` | One 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:

| Key | Starts inserting |
| --- | --- |
| `i` | Before the cursor |
| `a` | After the cursor (append) |
| `I` | At the start of the line |
| `A` | At the end of the line |
| `o` | On a new line **below** |
| `O` | On 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.

| Key | Action |
| --- | --- |
| `x` | Delete the character under the cursor |
| `dd` | Delete (cut) the whole line |
| `3dd` | Delete 3 lines |
| `dw` | Delete to the end of the word |
| `d$` or `D` | Delete to the end of the line |
| `dG` | Delete to the end of the file |
| `yy` | Yank (copy) the line |
| `3yy` | Yank 3 lines |
| `yw` | Yank a word |
| `p` | Put after the cursor (or below, for whole lines) |
| `P` | Put 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`.

 (Side note: 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

| Key | Action |
| --- | --- |
| `r` + a character | Replace one character |
| `R` | Overwrite mode, until `Esc` |
| `cw` | Change a word: delete it and go to insert mode |
| `cc` | Change the whole line |
| `J` | Join the next line to this one |
| `u` | Undo |
| `Ctrl+R` | Redo (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

| Key | Action |
| --- | --- |
| `/text` + `Enter` | Search **forward** for `text` |
| `?text` + `Enter` | Search **backward** |
| `n` | Next match, in the same direction |
| `N` | Next match, in the opposite direction |

The search text is a [regular expression](../regular-expressions/), 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`:

| Command | Action |
| --- | --- |
| `:w` | Write (save) |
| `:w newname` | Save under another name |
| `:w!` | Force the write, for example over a read-only file you own (or as root) |
| `:q` | Quit (refuses if there are unsaved changes) |
| `:q!` | Quit and **throw away** changes |
| `:wq` or `:x` | Save and quit |
| `ZZ` | Save (if changed) and quit, like `:x`. No colon, no Enter |
| `ZQ` | Quit 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:

| Command | Action |
| --- | --- |
| `:set number` / `:set nonumber` | Show / hide line numbers |
| `:r file` | Read another file in below the cursor |
| `:!command` | Run a shell command, then return to vi |
| `:e file` | Open another file |
| `:help` | Built-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:

```bash {title="~/.bashrc"}
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

1. You've made a mess of a file in `vi` and want to leave **without saving**. What do you type?
   - `:wq`
   - **`:q!`** (correct)
   - `ZZ`
   `:q!` quits and throws away the changes. `:wq` and `ZZ` both save before quitting.

2. In normal mode, which key opens a new line **below** the cursor and switches to insert mode?
   - `i`
   - `a`
   - **`o`** (correct)
   `o` opens a line below, `O` a line above. `i` inserts before the cursor and `a` appends after it, both on the current line.

3. What does `3yy` followed by `p` do?
   - **Copies three lines and pastes them below the cursor** (correct)
   - Deletes three lines and pastes them back
   - Copies the line three times
   `yy` yanks (copies) a line and a count in front repeats it, so `3yy` copies three lines. `p` puts them after the cursor.


