Learn / Linux / Getting Started
Lesson 7 of 74

Editing Files: nano and vim

Edit files directly on a server. nano for quick changes, then vim properly: its modes, moving, editing, copy and paste, undo, search and replace, visual mode, saving and quitting, swap files, plus how to choose the editor that tools like crontab and git open.

30 min read Report a problem Hands-on lab included 6-question quiz

Why terminal editors?

On your own computer you edit files in VS Code or Notepad. On a server you're connected through SSH: no windows, no mouse, and the file you need to fix (a config in /etc, a broken script, a cron job) is on the server. So you edit it right there in the terminal.

Two editors cover everything:

nanovim
Learning curvenone: type to edit, shortcuts shown on screensteep for a day, then very fast
Availablemost Ubuntu/Debian servers; often missing on minimal systemspractically everywhere: every distro, most container images with an editor, routers and appliances (as vi)
Best forquick, small editseverything, especially big edits, once you know the basics
Opened by default byUbuntu's crontab -e and visudomany other systems, git commit, and anything on Red Hat-based servers

You should be comfortable with nano and able to work in vim. Every DevOps engineer is expected to at least open, edit, save and quit vim without panic.

Before editing any important file, back it up:

text
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

nano

text
nano /etc/myapp/app.conf

If the file doesn't exist, nano creates it when you save. The screen looks like this:

  GNU nano 7.2                 /etc/myapp/app.conf
port=8080
environment=production
workers=4

^G Help ^O Write Out ^W Where Is ^K Cut ^T Execute ^C Location ^X Exit ^R Read File ^\ Replace ^U Paste ^J Justify ^/ Go To Line

The top line shows the file name. The bottom two lines are the shortcut bar: ^ means the Ctrl key, so ^O is Ctrl + O.

Edit like any simple editor: arrow keys to move, type to insert, Backspace/Delete to remove. Then:

The nano shortcuts you need

KeysAction
Ctrl + Osave ("Write Out"). Press Enter to keep the file name.
Ctrl + Xexit. With unsaved changes it asks Save modified buffer?: Y (then Enter), N to discard, Ctrl + C to go back.
Ctrl + Wsearch ("Where Is"). Alt + W repeats the search.
Ctrl + \search and replace (asks for each match, or A for all)
Ctrl + Kcut the current line (repeat to cut several)
Ctrl + Upaste what you cut
Alt + U / Alt + Eundo / redo
Ctrl + / or Ctrl + _go to a line number
Ctrl + Cshow the cursor position (line and column)
Alt + Astart selecting text (then Ctrl + K cuts the selection)

Useful ways to open files:

text
nano -l app.conf        # show line numbers
nano +37 app.conf       # open with the cursor on line 37 (from an error message)
Try it · Task 1 of 3

Quick edits with nano

Raise the shop's worker count to 8 and add a maintenance setting.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

nano works like the simple editors you know: open a file, move with the arrow keys, type to insert text, Backspace to delete. The only new thing is that saving and quitting are done with keyboard shortcuts, and nano lists the most important ones at the bottom of the screen, so you never have to memorise them.

1. Look at the file first

bash
cat /etc/shopapp/shopapp.conf
text
# Shop application settings
port=8080
environment=production
workers=4
payment_provider=sandbox

You need to change workers=4 to workers=8 and add a new line maintenance=false. And since it's a config file: back it up first.

bash
cp /etc/shopapp/shopapp.conf /etc/shopapp/shopapp.conf.bak

2. Open it in nano

bash
nano /etc/shopapp/shopapp.conf

What it does: opens the file in nano. If the file doesn't exist, nano creates it when you save. (The Run button types the command for you. Everything after that happens with your keyboard, inside the terminal.)

text
  GNU nano 7.2                  /etc/shopapp/shopapp.conf
# Shop application settings
port=8080
environment=production
workers=4
payment_provider=sandbox




^G Help        ^O Write Out   ^W Where Is    ^K Cut         ^T Execute     ^C Location
^X Exit        ^R Read File   ^\ Replace     ^U Paste       ^J Justify     ^/ Go To Line
  • Top line: the nano version and the file name.
  • Middle: the file's contents, with your cursor at the start.
  • Bottom two lines: the shortcut bar. ^O Write Out means Ctrl + O saves ("writes out") the file, and ^X Exit means Ctrl + X quits.

3. Make the edits

  1. Use the arrow keys to move to the line workers=4, then to the end of it.
  2. Press Backspace once to delete the 4, and type 8.
  3. Move to the end of the last line (payment_provider=sandbox), press Enter and type maintenance=false.

4. Save and exit

KeysWhat happens
Ctrl + Onano asks File Name to Write: /etc/shopapp/shopapp.conf. Press Enter to keep the name. The bottom shows [ Wrote 6 lines ].
Ctrl + Xquit and return to your prompt

If you press Ctrl + X with unsaved changes, nano asks Save modified buffer?. Press Y to save (then Enter for the name), N to throw the changes away, or Ctrl + C to go back to editing.

5. More nano shortcuts

KeysAction
Ctrl + Wsearch for text ("Where Is")
Ctrl + Kcut the whole current line
Ctrl + Upaste the line(s) you cut ("Uncut")
Ctrl + \search and replace
Alt + Uundo
Ctrl + / or Ctrl + _go to a line number, handy for "error on line 37"

6. Check your change

bash
cat /etc/shopapp/shopapp.conf
diff /etc/shopapp/shopapp.conf.bak /etc/shopapp/shopapp.conf

What diff does: compares two files line by line and shows only what's different. Perfect for checking a config change before you apply it.

text
4c4
< workers=4
---
> workers=8
5a6
> maintenance=false
  • 4c4: line 4 was changed. < shows the old version (from the first file), > the new one.
  • 5a6: after line 5, a line was added, becoming line 6 of the new file.

Exactly the two edits you intended, nothing else.

2 · Your task

Edit /etc/shopapp/shopapp.conf with nano so that workers is 8, and add a new line maintenance=false. Keep all the other lines.

Expected result: cat /etc/shopapp/shopapp.conf shows workers=8 and maintenance=false, plus the original settings.

First start the lab machine in the terminal panel on the right.

vim: the idea of modes

vim (Vi IMproved) confuses beginners for one reason: it has modes. The same key does different things depending on the mode you're in. That's also what makes it fast: in normal mode, every key is a command, so you edit without reaching for the mouse or holding Ctrl.

vim's modes

Insert modekeys type text
bottom shows -- INSERT --
i, a, o
Esc
Normal modewhere vim starts
keys are commands: move, delete, copy
: (colon)
Enter / Esc
Command-line modetype commands at the bottom
:w save, :q quit, :%s replace

Esc always brings you back to normal mode. When in doubt, press Esc twice.

There's also visual mode (v) for selecting text, covered below.

vim: surviving

The minimum that gets you through any situation:

text
vim app.conf
  1. Press i to enter insert mode. The bottom line shows -- INSERT --.
  2. Make your changes with the arrow keys and typing.
  3. Press Esc to go back to normal mode.
  4. Type :wq and press Enter to save and quit.

And the quit commands, worth memorising:

CommandMeaning
:wwrite (save)
:qquit (refuses if there are unsaved changes)
:wq or :xsave and quit
:q!quit and discard changes. The ! means "I'm sure".
:w newname.confsave as a different file
ZZ (in normal mode)save and quit, no colon needed

If you try :q with unsaved changes, vim protects you:

text
E37: No write since last change (add ! to override)

Choose :wq to keep your changes or :q! to drop them.

vim: entering insert mode

i isn't the only way in. Each key puts the cursor somewhere different:

KeyStarts inserting
ibefore the cursor
aafter the cursor ("append")
Iat the start of the line
Aat the end of the line, very handy for adding to a config value
oon a new line below, the fastest way to add a line
Oon a new line above
Try it · Task 2 of 3

Surviving vim

Create a file with vim, write a line in it, save and quit.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

vim confuses newcomers for one reason: it has modes. The same key does different things depending on the mode you're in.

ModeWhat your keys doHow to get there
Normal (the start mode)keys are commands: move, delete, copy. Typing dd deletes a line instead of inserting "dd".press Esc (from any mode)
Insertkeys type text, like a normal editorpress i in normal mode
Command-linetype a command at the bottom, such as save or quitpress : in normal mode

The golden rule: if you're lost, press Esc a couple of times. You're back in normal mode, and from there everything below works.

1. Open a new file

bash
vim /root/vim-was-easy.txt

What it does: opens vim on a file that doesn't exist yet. vim creates it when you save.

text
~
~
~
~
"/root/vim-was-easy.txt" [New]
  • Each ~ marks a line past the end of the file. The file is empty, so it's all ~.
  • The bottom line shows the file name and [New].
  • You're in normal mode. If you start typing now, letters will be treated as commands, so don't type yet.

2. Insert text

  1. Press i. The bottom line changes to -- INSERT --: now your keys type text.
  2. Type: I can exit vim
  3. Press Esc. -- INSERT -- disappears, and you're back in normal mode.

3. Save and quit

Commands that start with : appear at the bottom of the screen. Type them and press Enter:

CommandMeaning
:wwrite (save) the file
:qquit. vim refuses if there are unsaved changes.
:wqwrite and quit, the one you'll use most (:x does the same)
:q!quit and throw away your changes. The ! means "yes, I'm sure".

Type :wq and press Enter.

text
"/root/vim-was-easy.txt" [New] 1L, 15B written

vim confirms it wrote 1 line (1L) and 15 bytes (15B), then exits to your prompt.

4. If vim complains

If you type :q while you have unsaved changes, vim shows:

text
E37: No write since last change (add ! to override)

That's vim protecting your work. Choose :wq to save, or :q! to leave without saving.

5. Check

bash
cat /root/vim-was-easy.txt
text
I can exit vim

"How do I exit vim?" is one of the most asked programming questions ever. The answer is: Esc, then :q! to leave without saving or :wq to save and leave. Now you know.

2 · Your task

Use vim to create /root/vim-was-easy.txt containing the line I can exit vim, then save and quit.

Expected result: cat /root/vim-was-easy.txt prints I can exit vim.

First start the lab machine in the terminal panel on the right.

vim: moving around (normal mode)

KeysMoves
arrow keys, or h j k lleft, down, up, right
w / bnext / previous word
0 / $start / end of the line
gg / Gfirst / last line of the file
37G or :37line 37
Ctrl + d / Ctrl + uhalf a screen down / up
%jump to the matching bracket ( ), { }, [ ]

Show line numbers with :set number (:set nonumber hides them).

vim: editing in normal mode

This is where vim gets fast. Commands are short and they combine:

KeysAction
xdelete the character under the cursor
dddelete (cut) the whole line
5dddelete 5 lines
dwdelete to the end of the word
Ddelete to the end of the line
cwchange the word: delete it and enter insert mode
yyyank (copy) the line
5yycopy 5 lines
p / Ppaste below / above the cursor
r + a letterreplace one character
uundo. Press it again to undo more.
Ctrl + rredo
.repeat the last change
>> / <<indent / unindent the line

Notice the pattern: a number repeats a command (5dd), and operators like d (delete), c (change) and y (yank) combine with movements like w (word) or $ (end of line). d$ deletes to the end of the line, y$ copies to the end of the line. Once you see the grammar, you don't memorise commands, you build them.

vim: visual mode, selecting text

KeysSelects
vcharacters, as you move
Vwhole lines
Ctrl + va rectangular block (columns)

Select with the movement keys, then act on the selection: d cut, y copy, > indent, : run a command on just those lines. Esc cancels.

vim: search and replace

KeysAction
/word + Entersearch forward
?word + Entersearch backward
n / Nnext / previous match
*search for the word under the cursor

The substitute command is one of the most useful things in vim, and the same syntax works in sed:

text
:%s/old/new/g
PartMeaning
:start a command
%on every line. Leave it out for the current line only, or give a range like 10,20.
ssubstitute
/old/new/find old, replace with new
gevery match on each line, not only the first

Useful variants:

CommandEffect
:%s/http:/https:/greplace everywhere
:%s/http:/https:/gcask to confirm each one (y / n / a for all)
:%s/debug/info/gicase-insensitive
:10,20s/^/# /comment out lines 10 to 20 (^ means "start of line")

vim tells you what it did, for example 2 substitutions on 2 lines.

Try it · Task 3 of 3

vim power moves

Fix the server list: rename the database everywhere and delete the retired server.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

vim's modes feel strange at first, but they are what makes it fast: in normal mode every key is a command, so you edit with a few keystrokes instead of reaching for the mouse. A dozen commands cover most real work on servers: moving, deleting lines, undoing, searching and replacing across a whole file.

The database was migrated: old-db.internal is now called db.internal, and web-3 has been retired. Look at the file first:

bash
cat -n /etc/shopapp/servers.txt
text
     1	# Servers the shop app talks to
     2	web-1.internal     role=web
     3	web-2.internal     role=web
     4	old-db.internal    role=database
     5	cache-1.internal   role=cache
     6	web-3.internal     role=web    decommissioned
     7	old-db.internal    role=database-replica

Two lines mention old-db.internal, and line 6 has to go. Open it in vim:

bash
vim /etc/shopapp/servers.txt

1. Move around (normal mode)

KeysMoves to
arrow keys, or h j k lleft, down, up, right
ggthe first line
Gthe last line
6G or :6 then Enterline 6
0 / $start / end of the current line
w / bnext / previous word

Type :set number and press Enter to show line numbers on the left. (:set nonumber hides them again.)

2. Search

KeysAction
/text then Entersearch forward for "text"
n / Nnext / previous match

Type /decommissioned and press Enter: the cursor jumps to line 6.

3. Delete, copy, paste, undo

KeysAction
dddelete (cut) the current line
yycopy ("yank") the current line
ppaste below the cursor
xdelete the character under the cursor
uundo the last change (press again to undo more)
Ctrl + Rredo

With the cursor on line 6, press dd. The line disappears. Press u to see it come back, then dd again to delete it for real.

4. Replace across the whole file

text
:%s/old-db.internal/db.internal/g
PartMeaning
:start a command
%on every line of the file (without it, only the current line)
ssubstitute (replace)
/old-db.internal/what to find
db.internal/what to replace it with
gglobal: every match on each line, not just the first one

Add c at the end (/gc) and vim asks you to confirm each replacement with y or n.

text
2 substitutions on 2 lines

vim tells you how many replacements it made: both old-db.internal lines are fixed. Exactly the same syntax works in sed, which you'll meet in the text processing track.

5. Save and check

Type :wq and press Enter, then:

bash
cat /etc/shopapp/servers.txt
text
# Servers the shop app talks to
web-1.internal     role=web
web-2.internal     role=web
db.internal    role=database
cache-1.internal   role=cache
db.internal    role=database-replica

Six lines: the database renamed everywhere, and web-3 gone. (The columns no longer line up because the name got 4 characters shorter. The program reading the file doesn't care about spacing.)

2 · Your task

Using vim, fix /etc/shopapp/servers.txt:

  1. Replace every old-db.internal with db.internal.
  2. Delete the line of the decommissioned server.

Expected result: the file has 6 lines, no old-db anywhere and no decommissioned line, and all other servers are still there.

Hint: the commands, explained

Inside vim, in normal mode:

text
:%s/old-db.internal/db.internal/g
/decommissioned
dd
:wq

What each part does

  • All of this is typed inside vim (press Esc first so you're in Normal mode).
  • :%s/old/new/g: : command mode, % every line, s substitute, g every match on each line.
  • /decommissioned + Enter: jump to the next line containing that word.
  • dd: delete that whole line. :wq: write (save) and quit.
First start the lab machine in the terminal panel on the right.

vim: swap files ("E325: ATTENTION")

While you edit app.conf, vim keeps a hidden recovery file next to it called .app.conf.swp. If your SSH connection drops, or someone else is editing the same file, the next time you open it you'll see:

text
E325: ATTENTION
Found a swap file by the name ".app.conf.swp"
...
[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:

Don't panic. Ask yourself: is someone else editing this file right now? (Check with ps aux | grep vim.) If yes, press Q and talk to them. If not, it's left over from a crash: press R to recover your unsaved changes, check the file, save it, then delete the swap file (rm .app.conf.swp). Or press D to delete the swap file if you don't need it.

vim: a few settings

You can type settings while editing, or put them in ~/.vimrc (without the colon) to make them permanent:

SettingEffect
:set numberline numbers
:syntax oncolour highlighting
:set pastestop vim auto-indenting when you paste text from your clipboard (:set nopaste after)
:set expandtab tabstop=2 shiftwidth=2indent with 2 spaces, essential for YAML files

Choosing the default editor

Many tools open an editor for you: crontab -e, visudo, git commit, systemctl edit, kubectl edit. Which one they open depends on the EDITOR environment variable:

text
export EDITOR=nano          # for this session
echo 'export EDITOR=nano' >> ~/.bashrc     # permanently

On Ubuntu, select-editor asks you to choose, and sudo update-alternatives --config editor sets the system default.

Pasting a YAML file into vim and finding the indentation destroyed: vim auto-indented each pasted line. Run :set paste before pasting, or use vim with a .vimrc that sets it up. And never use tabs in YAML: :set expandtab turns the Tab key into spaces.

"How do you exit vim?" Esc, then :wq to save and quit, or :q! to quit without saving.

"How do you replace a word everywhere in a file with vim?" :%s/old/new/g, adding c to confirm each change.

"Which editor would you use on a server?" vim or vi, because it's on every system, but nano is fine for quick edits where it's installed. What matters is making a backup before changing configs and validating them afterwards (for example nginx -t, sshd -t).

Summary

  • Back up before editing (cp file file.bak); compare after with diff file.bak file.
  • nano: type to edit; Ctrl + O save, Ctrl + X exit, Ctrl + W search, Ctrl + \ replace, Ctrl + K/Ctrl + U cut/paste lines, nano +LINE file.
  • vim modes: normal (commands, Esc), insert (i, a, o, A), command-line (:), visual (v, V).
  • vim survival: :w, :q, :wq, :q!.
  • vim editing: dd, yy, p, x, u, Ctrl + r, .; numbers repeat (5dd); operators combine with movements (dw, d$, cw).
  • vim search and replace: /word, n, :%s/old/new/g (c to confirm).
  • Swap file warning: someone else editing, or a crash; recover with R, then delete the .swp file.
  • EDITOR decides which editor crontab -e, git commit and friends open.
Check your understanding

Quick quiz

Feedback