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.
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:
| nano | vim | |
|---|---|---|
| Learning curve | none: type to edit, shortcuts shown on screen | steep for a day, then very fast |
| Available | most Ubuntu/Debian servers; often missing on minimal systems | practically everywhere: every distro, most container images with an editor, routers and appliances (as vi) |
| Best for | quick, small edits | everything, especially big edits, once you know the basics |
| Opened by default by | Ubuntu's crontab -e and visudo | many 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:
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.baknano
nano /etc/myapp/app.confIf 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
| Keys | Action |
|---|---|
Ctrl + O | save ("Write Out"). Press Enter to keep the file name. |
Ctrl + X | exit. With unsaved changes it asks Save modified buffer?: Y (then Enter), N to discard, Ctrl + C to go back. |
Ctrl + W | search ("Where Is"). Alt + W repeats the search. |
Ctrl + \ | search and replace (asks for each match, or A for all) |
Ctrl + K | cut the current line (repeat to cut several) |
Ctrl + U | paste what you cut |
Alt + U / Alt + E | undo / redo |
Ctrl + / or Ctrl + _ | go to a line number |
Ctrl + C | show the cursor position (line and column) |
Alt + A | start selecting text (then Ctrl + K cuts the selection) |
Useful ways to open files:
nano -l app.conf # show line numbers
nano +37 app.conf # open with the cursor on line 37 (from an error message)Quick edits with nano
Raise the shop's worker count to 8 and add a maintenance setting.
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
cat /etc/shopapp/shopapp.conf# Shop application settings
port=8080
environment=production
workers=4
payment_provider=sandboxYou 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.
cp /etc/shopapp/shopapp.conf /etc/shopapp/shopapp.conf.bak2. Open it in nano
nano /etc/shopapp/shopapp.confWhat 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.)
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 OutmeansCtrl + Osaves ("writes out") the file, and^X ExitmeansCtrl + Xquits.
3. Make the edits
- Use the arrow keys to move to the line
workers=4, then to the end of it. - Press
Backspaceonce to delete the4, and type8. - Move to the end of the last line (
payment_provider=sandbox), pressEnterand typemaintenance=false.
4. Save and exit
| Keys | What happens |
|---|---|
Ctrl + O | nano asks File Name to Write: /etc/shopapp/shopapp.conf. Press Enter to keep the name. The bottom shows [ Wrote 6 lines ]. |
Ctrl + X | quit 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
| Keys | Action |
|---|---|
Ctrl + W | search for text ("Where Is") |
Ctrl + K | cut the whole current line |
Ctrl + U | paste the line(s) you cut ("Uncut") |
Ctrl + \ | search and replace |
Alt + U | undo |
Ctrl + / or Ctrl + _ | go to a line number, handy for "error on line 37" |
6. Check your change
cat /etc/shopapp/shopapp.conf
diff /etc/shopapp/shopapp.conf.bak /etc/shopapp/shopapp.confWhat diff does: compares two files line by line and shows only what's different. Perfect for checking a config change before you apply it.
4c4
< workers=4
---
> workers=8
5a6
> maintenance=false4c4: 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.
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.
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
bottom shows
-- INSERT --keys are commands: move, delete, copy
:w save, :q quit, :%s replaceEsc 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:
vim app.conf- Press
ito enter insert mode. The bottom line shows-- INSERT --. - Make your changes with the arrow keys and typing.
- Press
Escto go back to normal mode. - Type
:wqand pressEnterto save and quit.
And the quit commands, worth memorising:
| Command | Meaning |
|---|---|
:w | write (save) |
:q | quit (refuses if there are unsaved changes) |
:wq or :x | save and quit |
:q! | quit and discard changes. The ! means "I'm sure". |
:w newname.conf | save as a different file |
ZZ (in normal mode) | save and quit, no colon needed |
If you try :q with unsaved changes, vim protects you:
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:
| 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, very handy for adding to a config value |
o | on a new line below, the fastest way to add a line |
O | on a new line above |
Surviving vim
Create a file with vim, write a line in it, save and quit.
vim confuses newcomers for one reason: it has modes. The same key does different things depending on the mode you're in.
| Mode | What your keys do | How 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) |
| Insert | keys type text, like a normal editor | press i in normal mode |
| Command-line | type a command at the bottom, such as save or quit | press : 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
vim /root/vim-was-easy.txtWhat it does: opens vim on a file that doesn't exist yet. vim creates it when you save.
~
~
~
~
"/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
- Press
i. The bottom line changes to-- INSERT --: now your keys type text. - Type:
I can exit vim - 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:
| Command | Meaning |
|---|---|
:w | write (save) the file |
:q | quit. vim refuses if there are unsaved changes. |
:wq | write 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.
"/root/vim-was-easy.txt" [New] 1L, 15B writtenvim 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:
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
cat /root/vim-was-easy.txtI 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.
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.
vim: moving around (normal mode)
| Keys | Moves |
|---|---|
arrow keys, or h j k l | left, down, up, right |
w / b | next / previous word |
0 / $ | start / end of the line |
gg / G | first / last line of the file |
37G or :37 | line 37 |
Ctrl + d / Ctrl + u | half 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:
| Keys | Action |
|---|---|
x | delete the character under the cursor |
dd | delete (cut) the whole line |
5dd | delete 5 lines |
dw | delete to the end of the word |
D | delete to the end of the line |
cw | change the word: delete it and enter insert mode |
yy | yank (copy) the line |
5yy | copy 5 lines |
p / P | paste below / above the cursor |
r + a letter | replace one character |
u | undo. Press it again to undo more. |
Ctrl + r | redo |
. | 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
| Keys | Selects |
|---|---|
v | characters, as you move |
V | whole lines |
Ctrl + v | a 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
| Keys | Action |
|---|---|
/word + Enter | search forward |
?word + Enter | search backward |
n / N | next / 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:
:%s/old/new/g| Part | Meaning |
|---|---|
: | start a command |
% | on every line. Leave it out for the current line only, or give a range like 10,20. |
s | substitute |
/old/new/ | find old, replace with new |
g | every match on each line, not only the first |
Useful variants:
| Command | Effect |
|---|---|
:%s/http:/https:/g | replace everywhere |
:%s/http:/https:/gc | ask to confirm each one (y / n / a for all) |
:%s/debug/info/gi | case-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.
vim power moves
Fix the server list: rename the database everywhere and delete the retired server.
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:
cat -n /etc/shopapp/servers.txt 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-replicaTwo lines mention old-db.internal, and line 6 has to go. Open it in vim:
vim /etc/shopapp/servers.txt1. Move around (normal mode)
| Keys | Moves to |
|---|---|
arrow keys, or h j k l | left, down, up, right |
gg | the first line |
G | the last line |
6G or :6 then Enter | line 6 |
0 / $ | start / end of the current line |
w / b | next / previous word |
Type :set number and press Enter to show line numbers on the left. (:set nonumber hides them again.)
2. Search
| Keys | Action |
|---|---|
/text then Enter | search forward for "text" |
n / N | next / previous match |
Type /decommissioned and press Enter: the cursor jumps to line 6.
3. Delete, copy, paste, undo
| Keys | Action |
|---|---|
dd | delete (cut) the current line |
yy | copy ("yank") the current line |
p | paste below the cursor |
x | delete the character under the cursor |
u | undo the last change (press again to undo more) |
Ctrl + R | redo |
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
:%s/old-db.internal/db.internal/g| Part | Meaning |
|---|---|
: | start a command |
% | on every line of the file (without it, only the current line) |
s | substitute (replace) |
/old-db.internal/ | what to find |
db.internal/ | what to replace it with |
g | global: 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.
2 substitutions on 2 linesvim 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:
cat /etc/shopapp/servers.txt# 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-replicaSix 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.)
Using vim, fix /etc/shopapp/servers.txt:
- Replace every
old-db.internalwithdb.internal. - 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:
:%s/old-db.internal/db.internal/g
/decommissioned
dd
:wqWhat 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,ssubstitute,gevery match on each line./decommissioned+ Enter: jump to the next line containing that word.dd: delete that whole line.:wq: write (save) and quit.
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:
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:
| Setting | Effect |
|---|---|
:set number | line numbers |
:syntax on | colour highlighting |
:set paste | stop vim auto-indenting when you paste text from your clipboard (:set nopaste after) |
:set expandtab tabstop=2 shiftwidth=2 | indent 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:
export EDITOR=nano # for this session
echo 'export EDITOR=nano' >> ~/.bashrc # permanentlyOn 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 withdiff file.bak file. - nano: type to edit;
Ctrl + Osave,Ctrl + Xexit,Ctrl + Wsearch,Ctrl + \replace,Ctrl + K/Ctrl + Ucut/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(cto confirm). - Swap file warning: someone else editing, or a crash; recover with
R, then delete the.swpfile. EDITORdecides which editorcrontab -e,git commitand friends open.
Quick quiz
You've practised everything in this lesson
Every task was checked on your own machine. You can end the lab, or keep experimenting in the terminal.