Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 95 ยท Working with Files

Editing Files: nano, vim and Emacs Basics

Edit files in the terminal with confidence: nano shortcuts, the vim modes and survival kit, Emacs basics, how $EDITOR works and how to get out when stuck.

Sooner or later you log in to a server that has no graphical desktop, and the only way to change a configuration file is to edit it inside the terminal. Git opens an editor for your commit message, crontab -e opens one for your schedule, and visudo opens one before it lets you touch sudo permissions. If you do not know how to type text and, above all, how to quit, you are stuck. This lesson is a survival kit for three editors you will meet: nano, vim and Emacs.

You do not need to love any of them. You need to be able to open a file, change it, save it and leave, on any machine. Then, if you pick one editor to learn deeply, you can grow from there. Our browser sandbox cannot run an interactive full-screen program, so the editor commands below are read-only. To still let you practise, we build a tiny model of vim's modes in Bash that you can feed with keystrokes, and we also script file edits with the same ideas using normal command-line tools.

Which editor will you get?

Programs that need to edit text look at two environment variables (see Environment Variables). VISUAL is checked first, then EDITOR, and if neither is set the program falls back to something like nano, vi or editor. Set your preference once in ~/.bashrc:

CONSOLE
$ export EDITOR=nano
$ export VISUAL=nano
$ git config --global core.editor nano

Ask the system which editors exist with command -v nano vim vi emacs. Almost every Linux system has vi (usually a small version of vim), so vi is the one editor you can count on. That is the main reason to learn its basics.

nano: the friendly one

nano shows its own cheat sheet at the bottom of the screen, which makes it the best choice for a first edit. The caret ^ means the Ctrl key, and M- means Alt (or Esc, then the key).

CONSOLE
$ nano notes.txt              # open (or create) a file
$ nano +25 app.conf           # open at line 25
$ sudo nano /etc/hosts        # edit a system file as root

You type text directly; the arrow keys move the cursor. The shortcuts you need:

Keys Action
Ctrl+O, then Enter save ("Write Out")
Ctrl+X exit (it asks to save if you changed anything)
Ctrl+K / Ctrl+U cut the current line / paste it back
Ctrl+W search; Alt+W for the next match
Ctrl+\ search and replace
Ctrl+_ go to line number
Alt+U / Alt+E undo / redo
Ctrl+G built-in help

To save and quit: Ctrl+O, Enter, Ctrl+X. To abandon changes: Ctrl+X, then N. That is all of nano you need on day one.

If nano is missing, install it with your package manager (sudo apt install nano on Debian and Ubuntu, sudo dnf install nano on Fedora and CentOS Stream; sudo pacman -S nano on Arch). Its settings live in ~/.nanorc (per user) or /etc/nanorc (system wide): set linenumbers shows line numbers, set tabsize 4 and set tabstospaces control indentation, set mouse enables mouse clicks and set softwrap wraps long lines on screen. Colour themes are include lines, for example include "/usr/share/nano/*.nanorc".

vim: modes, not menus

vim (Vi IMproved) is installed almost everywhere as vi or vim, and its first surprise is that it has modes. The same key does different things depending on the mode:

  • Normal mode is where you start. Keys are commands (move, delete, copy). Typing letters does not insert them.
  • Insert mode is where typed letters become text. You enter it with i, a, o and leave it with Esc.
  • Command-line mode starts when you press : in normal mode. You type a command such as :w and press Enter.
  • Visual mode (v, V) selects text so that a command acts on the selection.
stateDiagram-v2
    [*] --> Normal
    Normal --> Insert: i, a, o, A
    Insert --> Normal: Esc
    Normal --> CommandLine: ":"
    CommandLine --> Normal: Enter or Esc
    Normal --> Visual: v, V
    Visual --> Normal: Esc

Normal mode is the hub. When you are lost, press Esc a couple of times to get back to it.

If you are ever stuck: press Esc twice, then type :q! and Enter. That quits and throws away all changes. Memorize it first, because it is the answer to the famous "how do I exit vim?" question.

CONSOLE
$ vim config.txt              # open a file
$ vim +/error app.log         # open and jump to the first match of "error"
$ vimtutor                    # a 30-minute interactive course; do it once

The survival kit

Keys (normal mode) Action
i / a insert before / after the cursor
A / I insert at the end / start of the line
o / O open a new line below / above and insert
Esc back to normal mode
h j k l or arrow keys left, down, up, right
0 / $ start / end of the line
gg / G first / last line (42G = line 42)
w / b next / previous word
x delete the character under the cursor
dd delete (cut) the current line
yy / p copy (yank) the line / paste it below
u / Ctrl+r undo / redo
/text then n search forward, jump to the next match
:w write (save)
:q quit (fails if there are unsaved changes)
:wq or ZZ save and quit
:q! quit without saving

Notice how the motions and actions combine like a small language. d means delete and takes a motion: dw deletes a word, d$ deletes to the end of the line, dd deletes the whole line. Put a count in front to repeat: 3dd deletes three lines, 5x deletes five characters. c means change (delete and start inserting), so cw replaces a word and ciw replaces the word under the cursor. The . key repeats your last change, which is the secret to editing the same thing in many places. Mix d, y and c with iw (inner word), ip (paragraph) or i" (inside quotes) and you already edit faster than most people with a mouse.

A model of the modes

Reading a table is not the same as feeling the modes. The function below is a deliberately small vim-like editor: it holds a few lines, interprets a string of keystrokes, and prints the result. It knows h j k l 0 $ x dd i a A o O Esc and the commands :w, :q, :wq and :q!. The escape key is written as \e. Our task is to change debug=true into debug=false and save.

Bash Keystrokes in, file out: a tiny modal editor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Read the first run slowly. j moves down, $ jumps to the last character, four x presses delete true, a starts inserting after the =, you type false, Esc returns to normal mode, and :wq plus Enter saves and quits. The second run shows the rule that surprises beginners: :q refuses to quit while there are unsaved changes, so you pick :wq (keep) or :q! (discard).

Search and replace

Searching starts with /. Substitution uses an ex command whose general form is :[range]s/pattern/replacement/[flags]. The patterns are regular expressions (see Regular Expressions):

CONSOLE
:s/old/new/            replace the first "old" on this line
:s/old/new/g           every "old" on this line
:%s/old/new/g          every "old" in the whole file (% = all lines)
:%s/old/new/gc         ask for confirmation at each match
:5,12s/tab/ /g         only lines 5 to 12
:g/^#/d                delete every line that starts with #
:g/^$/d                delete every empty line
:set number            show line numbers
:set paste             turn off auto-indent before pasting text

These commands are older than vim: they come from the line editor ex, which is also where sed got its syntax. That means you already know them from sed. The same edits work non-interactively, which is what you want in a script:

Bash The same ex-style edits, applied with sed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

When something goes wrong in an interactive session, remember that u undoes. Vim also creates a swap file (.file.swp) while you edit. If the editor crashed and you reopen the file, vim warns you that a swap file exists: recover from it with R or delete the swap file if you do not need it.

Customizing vim

Vim reads ~/.vimrc on start. A few lines make it much friendlier:

TEXT
set number          " line numbers
set tabstop=4       " how wide a tab looks
set shiftwidth=4    " indent size for >> and <<
set expandtab       " insert spaces when Tab is pressed
set hlsearch        " highlight search matches
syntax on

Beyond that there are thousands of plugins, but none of it is required. Many professionals use the plain defaults on servers and a heavily customized setup on their laptop.

Emacs: a quick survival guide

Emacs is the other classic. It has no modes: typing inserts text, and commands use Ctrl (C-) and Meta (M-, the Alt key or Esc) chords. It is rarely preinstalled on servers, but you may meet it on a colleague's machine. The essentials:

Keys Action
C-x C-f open (find) a file
C-x C-s save
C-x C-c quit Emacs
C-g cancel whatever is going on (the "get me out" key)
C-/ or C-x u undo
C-s / C-r search forward / backward
C-k kill (cut) to the end of the line
C-y yank (paste)
C-a / C-e start / end of line
M-x run a command by name

Open it in the terminal without a window with emacs -nw file.txt. Notice that "kill" and "yank" mean cut and paste: they come from Emacs and gave other tools these words.

Opening files safely

How an editor is started matters as much as which one you choose. Programs such as crontab, visudo and git commit do not edit your real file directly. They copy it to a temporary file, start $VISUAL or $EDITOR on the copy, wait for it to exit, check that the result is valid, and only then replace the original. If the editor fails or you quit without saving, the original is untouched. We can reproduce that flow, using a scripted "editor" so the example needs no keyboard:

Bash How $EDITOR is used by other programs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The same idea explains sudoedit file (or sudo -e): it edits a temporary copy as your own user and copies it back as root, so your editor and its plugins never run with root powers. Prefer it over sudo vim /etc/something.

A few more practical points:

  • Read-only viewing: use less to read, view file (vim read-only) to look without editing. See Viewing and Slicing Text.
  • Large files: nano and vim can load big files, but searching a gigabyte log is a job for grep and less.
  • Line endings and permissions: if you cannot save, you probably lack write permission. See File Permissions and Ownership. In vim, :w !sudo tee % saves the buffer through sudo tee when you forgot to open the file as root.
  • Copy and paste into the terminal: vim's auto-indent can mangle pasted code; :set paste before pasting avoids it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You are inside vim, made changes you do not want, and need to leave immediately. What do you type?

    Esc makes sure you are in normal mode, and :q! quits without saving. :wq would save the unwanted changes, and Ctrl+X is nano's exit key.
  2. 2. You open a file in vim and start typing, but nothing appears as text; letters seem to trigger odd actions. Why?

    vim starts in normal mode. Press i, a or o to enter insert mode, type your text, then press Esc to go back.
  3. 3. Which sequence saves the file in nano and exits?

    In nano, Ctrl+O writes the file (Enter confirms the name) and Ctrl+X exits. :wq is vim, and the last option is a mix of Emacs chords.
  4. 4. What does :%s/cat/dog/g do in vim?

    % means every line, s is substitute, and the g flag replaces all matches per line instead of only the first.
  5. 5. Which environment variable is checked first by programs that need to open an editor?

    Programs conventionally try VISUAL first, then EDITOR, and finally a built-in default such as vi or nano.

Summary

  • Set EDITOR (and VISUAL) so git, crontab -e and others open the editor you like; vi is the one editor you can rely on being installed.
  • nano is the easy option: Ctrl+O saves, Ctrl+X exits, Ctrl+W searches, and shortcuts are shown on screen.
  • vim has modes: normal for commands, i/a/o to insert, Esc to return, : for ex commands. Save with :w, leave with :q, force-quit with :q!, both with :wq.
  • Combine operators and motions (dw, d$, 3dd, ciw), repeat with ., undo with u, and substitute with :%s/old/new/g, the same syntax as sed.
  • Emacs uses chords: C-x C-f opens, C-x C-s saves, C-x C-c quits, and C-g cancels.
  • Programs such as visudo, crontab -e and sudoedit edit a temporary copy and validate it before replacing the real file.

Next: Viewing and Slicing Text