LFCA 20 ๐ง Editing Files with vim โ Basics
Vim is the editor you will meet on every Linux server, and it is also the one most likely to confuse a newcomer. The confusion is not accidental โ it comes from a single design decision that everything else depends on: vim is modal. When you open a file, you are not in a text field. You are in normal mode, where every key is a command rather than a character to insert. The letter i does not type “i”; it enters insert mode, where typing works the way you expect. The letter dd does not type “dd”; it deletes the current line. This chapter covers the basics you need to open a file, make a change, save, quit, and navigate without panic. It deliberately does not attempt to make you a vim power user โ that takes months, and the goal here is competence, not mastery.
Key point: vim starts in normal mode. Press i to insert text, Esc to return to normal mode, :w to save, :q to quit, and :wq to save and quit. If you are ever lost, press Esc a few times and then :q! to quit without saving. The mode indicator at the bottom left โ -- INSERT --, -- VISUAL --, or nothing โ tells you where you are. Learning to read that indicator is the first real skill.
Why vim is modal, and why that is a feature
The modal design is the source of vim’s reputation and its power. In a modeless editor, every keystroke has exactly one meaning: insert this character. That seems natural, but it leaves no keys free for commands. To delete a word, you must reach for a mouse, a menu, or a chorded shortcut like Ctrl+Backspace. In vim, normal mode is a dedicated command language. dw deletes a word. dd deletes a line. 3dd deletes three lines. d$ deletes to the end of the line. These are not arbitrary โ d is the delete operator and w, d, $ are motions that describe what to act on. Once you internalize the operator-motion grammar, editing becomes compositional in a way that modeless editors cannot match.
Why this matters for beginners. The first hour of vim is uncomfortable because you will type dd expecting to type the letters “dd” and instead delete a line. The recovery is u โ undo โ and that is the most important safety net you have. The discomfort fades once the mode indicator becomes a reflex rather than something you have to remember to check.
Why vim is everywhere. Vim (and its predecessor vi) ships on virtually every Unix and Linux system, including minimal containers and rescue environments where nano may be absent. The POSIX standard requires vi. When a server is broken and you need to edit a config file to fix it, vim is the editor that will be there. That alone justifies learning the survival commands.
Why “just use nano” is incomplete advice. Nano is easier, and for many one-off edits it is the correct choice. But vim is faster for sustained work, available in more places, and required knowledge for system administration roles. The two editors are not competitors โ they are tools for different jobs. Know both.
Opening files and the basic screen
The command is vim followed by a filename. If the file exists, it opens. If not, vim opens an empty buffer and creates the file on save.
$ vim /etc/ssh/sshd_config
The screen has no menu bar and no shortcut hints at the bottom (until you type :). The top line may show the filename and cursor position after you press Ctrl+G. The bottom line is reserved for command-line input when you type :, /, or ?. The absence of visible controls is deliberate: vim assumes you know the commands, and it gives that screen space back to the file.
Opening at a specific line. The +N syntax jumps directly to line N.
$ vim +42 /etc/ssh/sshd_config
Opening at the first match of a pattern. The +/pattern syntax searches for the pattern on open.
$ vim +/PermitRootLogin /etc/ssh/sshd_config
This places the cursor on the first line containing “PermitRootLogin”. It is the fastest way to get to a specific configuration directive when you know its name but not its line number.
Opening multiple files. vim file1 file2 opens both in separate buffers. :n moves to the next, :N or :prev to the previous. This matters when you are making coordinated changes across related config files and want to avoid re-opening vim repeatedly.
Why the +N and +/pattern forms are worth remembering. If a compiler error, a grep -n, or a log message has told you exactly where the problem is, these options turn “open vim, scroll around, search” into a single command. The less time you spend navigating, the more time you spend editing.
The three modes you will actually use
Vim has several modes, but beginners need three: normal, insert, and command-line. Visual mode is a fourth that you will meet soon after, but these three cover the essential loop.
Normal mode is where vim starts. Keys are commands. h, j, k, l move the cursor left, down, up, right โ arrow keys also work, but the home-row keys are faster once learned. x deletes the character under the cursor. dd deletes the line. u undoes. There is no visible indicator for normal mode; the bottom-left corner is empty.
Insert mode is where typing inserts text. Enter it with i (insert before cursor), a (append after cursor), o (open a new line below), or O (open a new line above). The bottom-left corner displays -- INSERT -- in white on black. Press Esc to return to normal mode. This is the mode you leave as soon as possible โ vim is not designed for staying in insert mode, because none of the navigation and editing commands work there.
Command-line mode is entered by typing : from normal mode. The cursor jumps to the bottom line, and you type commands like :w (save), :q (quit), :wq (save and quit), :q! (quit without saving), :s/old/new/g (substitute), or :set number (show line numbers). Press Enter to execute. Press Esc to cancel.
The essential loop:
vim file โ opens in normal mode
i โ enter insert mode (see -- INSERT --)
(type text)
Esc โ back to normal mode (indicator disappears)
:wq โ save and quit
Why Esc is the most important key. If you are unsure what mode you are in, press Esc. It always returns you to normal mode, and pressing it when you are already in normal mode does nothing harmful (you may hear a bell or see a screen flash). From normal mode, everything else is possible. From insert mode, only typing is possible.
Why the mode indicator matters more than the commands. Beginners who learn the commands but not the indicator still get lost, because they do not know whether their next keystroke will insert a character or execute a command. The indicator โ or its absence โ answers that question. Build the habit of glancing at the bottom-left corner before typing.
Saving, quitting, and the survival commands
The command-line mode commands for file operations are the ones you will use every session.
:w writes the file to disk. It stays in the editor. Use this when you want to save without quitting.
:q quits. It fails if there are unsaved changes, displaying an error message.
:wq saves and quits. This is the most common exit.
:q! quits without saving, discarding all changes since the last write. This is the emergency exit.
:x or ZZ (from normal mode) saves and quits, but only writes if there are changes. It is slightly more efficient than :wq for that reason, though the difference is negligible in practice.
Saving as a different filename. :w newname saves a copy as newname but continues editing the original. :sav newname saves as newname and switches to editing that file. The distinction matters when you want to branch a configuration file without losing your place in the original.
Saving with elevated permissions. If you opened a root-owned file as a regular user and forgot sudo, :w will fail. The fix is :w !sudo tee %. This pipes the buffer through sudo tee, writing the file with elevated privileges. It is a trick worth knowing because it saves you from losing your edits and reopening the file.
Why the cancel option is less prominent than in nano. Vim does not prompt “are you sure?” with a Ctrl+C escape. The prompt is the error message when :q fails. The equivalent of nano’s cancel is simply not typing :q! โ pressing Esc returns you to normal mode with your edits intact. The design assumes you know what you typed.
Navigation without arrow keys
Arrow keys work in vim, but the home-row keys are faster and are what tutorials expect you to use. The four movement keys are:
h โ left
j โ down
k โ up
l โ right
These are not mnemonics; they are historical artifacts of the ADM-3A terminal keyboard where vi was developed, which had arrows printed on those keys. The mapping stuck. They can be prefixed with counts: 4j moves down four lines, 3l moves right three characters.
Word movements. w moves to the beginning of the next word. b moves to the beginning of the previous word. e moves to the end of the current word. Capital versions W, B, E treat sequences of non-whitespace as words, which matters in code where punctuation breaks words differently than in prose.
Line and file movements. 0 moves to the beginning of the line. ^ moves to the first non-whitespace character. $ moves to the end of the line. gg goes to the top of the file. G goes to the bottom. 42G or :42 goes to line 42.
Why these matter when arrow keys exist. The arrow keys force your right hand off the home row. The vim movements keep both hands in typing position, which is faster and less fatiguing over a long session. If you plan to use vim seriously, the home-row keys are worth the initial awkwardness.
Simple edits: delete, change, undo
The delete operator is d. By itself it does nothing; it waits for a motion to describe what to delete. dd deletes the current line. dw deletes from the cursor to the next word. d$ deletes from the cursor to the end of the line. 3dd deletes three lines.
The change operator is c. It deletes the target and enters insert mode. cw changes the word under the cursor (deletes it and lets you type a replacement). cc changes the entire line. C changes from the cursor to the end of the line. This is often more useful than delete-then-insert because it combines the two steps.
The yank operator is y, vim’s word for copy. yy yanks the current line. yw yanks a word. y$ yanks to the end of the line. Paste with p (after cursor) or P (before cursor).
Undo and redo. u undoes the last change. Ctrl+r redoes the last undone change. U (capital) restores the current line to its state before any changes on that line, which is a separate and less commonly used operation. For most work, u and Ctrl+r are the pair that matters.
Why the operator-motion grammar is the real lesson. d and c are not the only operators, and w, $, dd are not the only motions. The grammar is what makes vim powerful. Once you understand that d means “delete what follows” and w means “the next word,” you can guess d} (delete to the next paragraph), dG (delete to the end of the file), and ct, (change to the next comma). The commands are not memorized individually; they are composed from a small vocabulary.
Search and replace
Search is entered with /pattern from normal mode. Press Enter, and vim jumps to the first match after the cursor. n repeats the search forward; N repeats it backward. ?pattern searches backward. * searches for the word currently under the cursor โ this is often faster than typing the pattern.
Substitute is the :s command. The basic form operates on the current line: :s/old/new/ replaces the first occurrence of “old” with “new” on the current line. Add g to replace all occurrences on the line: :s/old/new/g. Prefix with % to operate on the whole file: :%s/old/new/g.
Adding confirmation. The c flag makes vim prompt before each replacement: :%s/old/new/gc. You press y to replace, n to skip, a to replace all remaining, q to quit substituting, or l to replace this one and stop. This is the safe way to run a replace when you are not certain the pattern is specific enough.
Why :%s is worth learning before you need it. The most common real-world vim task is updating a value that appears many times in a config file โ an IP address, a path, a hostname. Doing it by hand is slow and error-prone. The substitute command is the right tool for that job.
Complete Example Session
# ============================================
# PART 1: OPEN AND EDIT
# ============================================
printf "server=localhost\nport=8080\n" > app.conf
vim app.conf
# Inside vim (starts in normal mode):
# Press i โ -- INSERT -- appears
# Type: # edited
# Press Esc โ -- INSERT -- disappears
# Type: :wq โ save and quit
cat app.conf
# # edited
# server=localhost
# port=8080
# ============================================
# PART 2: THE SURVIVAL SEQUENCE
# ============================================
vim app.conf
# Inside vim:
# Press i
# Type: broken edit
# Press Esc
# Type: :q! โ quit without saving
cat app.conf
# # edited
# server=localhost
# port=8080
# (the broken edit is gone)
# ============================================
# PART 3: NAVIGATE AND DELETE
# ============================================
vim app.conf
# Inside vim:
# Press j โ move down one line
# Press dd โ delete the current line
# Press u โ undo (line returns)
# Type: :wq โ save and quit
# ============================================
# PART 4: INSERT VARIANTS
# ============================================
vim app.conf
# Inside vim:
# Press G โ go to last line
# Press o โ open new line below, enter insert
# Type: timeout=30
# Press Esc
# Type: :wq
cat app.conf
# # edited
# server=localhost
# port=8080
# timeout=30
# ============================================
# PART 5: SEARCH
# ============================================
vim app.conf
# Inside vim:
# Type: /port โ search for "port"
# Press Enter โ cursor jumps to that line
# Press n โ next match (none, wraps)
# Type: :q!
# ============================================
# PART 6: SUBSTITUTE
# ============================================
vim app.conf
# Inside vim:
# Type: :%s/localhost/127.0.0.1/g
# Press Enter
# Type: :wq
cat app.conf
# # edited
# server=127.0.0.1
# port=8080
# timeout=30
# ============================================
# PART 7: OPEN AT A LINE
# ============================================
vim +3 app.conf
# Inside vim:
# Cursor is on line 3 (timeout=30)
# Type: :q!
# ============================================
# PART 8: LINE NUMBERS
# ============================================
vim app.conf
# Inside vim:
# Type: :set number
# Line numbers appear on the left
# Type: :q!
# ============================================
# PART 9: MULTIPLE FILES
# ============================================
printf "a=1\n" > one.txt
printf "b=2\n" > two.txt
vim one.txt two.txt
# Inside vim:
# Type: :n โ switch to two.txt
# Type: :N โ back to one.txt
# Type: :q!
# ============================================
# PART 10: WHAT NOT TO DO
# ============================================
# Do NOT stay in insert mode for navigation
# Arrow keys work in insert mode but it is not idiomatic
# Do NOT panic when :q fails
# Press Esc, then :q! to discard or :wq to save
# Do NOT use vim for bulk scripted edits
# That is sed's job
Each part exercises a survival command or a basic edit. The loop is always: enter mode, make change, return to normal, save or discard.
Quick Reference
Mode Entry and Exit
| From | To | Keys |
|---|---|---|
| Normal | Insert | i, a, o, I, A, O |
| Insert | Normal | Esc or Ctrl+[ |
| Normal | Command-line | : |
| Normal | Visual | v, V, Ctrl+v |
| Any | Normal | Esc (press repeatedly) |
Save and Quit
| Command | Action |
|---|---|
:w | Save |
:q | Quit (fails if unsaved) |
:wq | Save and quit |
:q! | Quit without saving |
:x or ZZ | Save if changed, then quit |
:w filename | Save as filename |
:w !sudo tee % | Save with sudo |
Navigation
| Key | Action |
|---|---|
h j k l | Left, down, up, right |
w / b | Next / previous word start |
e | End of word |
0 / $ | Start / end of line |
gg / G | Top / bottom of file |
42G or :42 | Go to line 42 |
Ctrl+f / Ctrl+b | Page down / up |
Editing
| Key | Action |
|---|---|
x | Delete character |
dd | Delete line |
dw | Delete word |
d$ | Delete to end of line |
cc | Change line |
cw | Change word |
yy | Yank (copy) line |
p / P | Paste after / before |
u | Undo |
Ctrl+r | Redo |
Search and Replace
| Command | Action |
|---|---|
/pattern | Search forward |
?pattern | Search backward |
n / N | Next / previous match |
* | Search word under cursor |
:s/old/new/ | Replace first on line |
:s/old/new/g | Replace all on line |
:%s/old/new/g | Replace all in file |
:%s/old/new/gc | Replace with confirmation |
Useful Command-Line Settings
| Command | Effect |
|---|---|
:set number | Show line numbers |
:set nonumber | Hide line numbers |
:set hlsearch | Highlight search matches |
:noh | Clear search highlighting |
:help | Open help |
:help :w | Help for :w |
Best Practices
โ Do This:
# Press Esc when unsure of mode
# Esc always returns to normal mode # โ
# Use the survival sequence
# :wq to save, :q! to discard # โ
# Search before scrolling
# /pattern then n to jump # โ
# Use :%s for repeated values
# :%s/old/new/gc with confirmation # โ
# Open at the line you need
vim +42 file # โ
# Learn one new command per session
# Start with dd, yy, p, u, Ctrl+r # โ
# Use :set number when line numbers help
# :set number or add to ~/.vimrc # โ
โ Don’t Do This:
# Don't stay in insert mode
# Esc to normal mode for navigation and commands # โ ๏ธ
# Don't panic when :q fails
# The error means unsaved changes; use :wq or :q! # โ ๏ธ
# Don't use arrow keys if you plan to learn vim seriously
# hjkl keeps hands on home row # โ ๏ธ
# Don't run :%s without checking the pattern
# Add c flag to confirm each replacement # โ ๏ธ
# Don't edit sudoers with vim
# Use visudo instead # โ ๏ธ
Common Pitfalls
| Pitfall | Problem | Solution |
|---|---|---|
| Typing in normal mode | Keys execute commands instead of inserting | Press i first |
:q fails | Unsaved changes | Use :wq or :q! |
| Lost in insert mode | Arrow keys work but commands do not | Press Esc |
dd deleted wrong line | No warning | u to undo |
:%s replaced too much | No confirmation | Add c flag |
| Cannot save root file | Opened without sudo | :w !sudo tee % |
| Forgot mode indicator | Typing commands as text | Glance bottom-left |
gg vs G confusion | Top vs bottom | gg = top, G = bottom |
Real-World Examples
1. Edit SSH config
sudo vim /etc/ssh/sshd_config
# Change PermitRootLogin, :wq, then restart sshd
2. Quick fix in a config
vim /etc/hosts
# Add a line, :wq
3. Open at a known line
vim +128 /etc/nginx/nginx.conf
4. Search and replace an IP
vim /etc/nginx/sites-available/default
# :%s/127.0.0.1/10.0.0.5/g
# :wq
5. Open at first match
vim +/PermitRootLogin /etc/ssh/sshd_config
6. Edit multiple files
vim file1.conf file2.conf
# :n to switch, :wq each
7. Save with sudo after forgetting
# Inside vim after failed :w
:w !sudo tee %
8. Discard all changes
# Inside vim
:q!
9. Search word under cursor
# Place cursor on word, press *
# n to cycle through matches
10. Show line numbers temporarily
# Inside vim
:set number
Visual: The Mode Loop
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ vim file โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโ โ
โ โ NORMAL MODE โโโโโโโโโโโโโโโโ โ
โ โ (default) โ โ โ
โ โโโโโโโโฌโโโโโโโ โ โ
โ โ โ โ
โ press i press Esc โ
โ โ โ โ
โ โผ โ โ
โ โโโโโโโโโโโโโโโ โ โ
โ โ INSERT MODE โโโโโโโโโโโโโโโโ โ
โ โ -- INSERT --โ โ
โ โโโโโโโโโโโโโโโ โ
โ โ
โ From normal mode: โ
โ :wq โ save and quit โ
โ :q! โ quit without saving โ
โ :w โ save only โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Visual: The Survival Sequence
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ I am lost. What do I do? โ
โ โ โ
โ โผ โ
โ Press Esc (a few times if needed) โ
โ โ โ
โ โผ โ
โ Am I in normal mode? โ
โ (no -- INSERT -- at bottom left) โ
โ โ โ
โ โโโ Yes โโโบ :q! to quit โ
โ โ :wq to save and quit โ
โ โ โ
โ โโโ No โโโโบ Press Esc again โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Visual: Operator + Motion
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ The grammar: โ
โ โ
โ OPERATOR + MOTION โ
โ โ
โ Operators: โ
โ d โ delete โ
โ c โ change (delete + insert) โ
โ y โ yank (copy) โ
โ โ
โ Motions: โ
โ w โ word โ
โ $ โ end of line โ
โ d โ line (dd = delete line) โ
โ G โ end of file โ
โ โ
โ Examples: โ
โ dw โ delete word โ
โ d$ โ delete to end of line โ
โ dd โ delete line โ
โ dG โ delete to end of file โ
โ cw โ change word โ
โ yy โ yank line โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Visual: Search and Replace Decision
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Need to find or replace text? โ
โ โ โ
โ โโโ Just find? โ
โ โ โโโ /pattern, n to cycle โ
โ โ โ
โ โโโ Replace? โ
โ โ โ
โ โโโ One line? โ
โ โ โโโ :s/old/new/g โ
โ โ โ
โ โโโ Whole file? โ
โ โ โโโ :%s/old/new/g โ
โ โ โ
โ โโโ Not sure? โ
โ โโโ :%s/old/new/gc โ
โ (confirm each) โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Task | Command |
|---|---|
| Open file | vim file |
| Open at line | vim +42 file |
| Enter insert | i, a, o |
| Return to normal | Esc |
| Save | :w |
| Quit | :q (fails if unsaved) |
| Save and quit | :wq |
| Quit without saving | :q! |
| Delete line | dd |
| Undo | u |
| Redo | Ctrl+r |
| Search | /pattern |
| Replace all | :%s/old/new/g |
| Show line numbers | :set number |
Key takeaways:
- Vim is modal โ normal mode for commands, insert mode for typing, command-line mode for saving and quitting
Escalways returns to normal mode โ press it when unsure, then decide what to do- The mode indicator tells you where you are โ
-- INSERT --means you are typing text, its absence means keys are commands - The survival sequence is
ito edit,Escto return,:wqto save,:q!to discard - Operator + motion is the editing grammar โ
ddeletes,cchanges,ycopies, and motions likew,$,dddescribe the target - Search with
/patternand substitute with:%s/old/new/gโ addcfor confirmation when unsure - Arrow keys work but home-row keys are faster โ
hjklkeeps hands in typing position - Vim is everywhere โ it ships on minimal systems where nano may be absent, which is why the survival commands are worth knowing even if you prefer another editor
Remember: Vim’s reputation for difficulty comes from its modal design, but the design is the source of its power. You do not need to master all of vim to be competent. You need the mode loop, the survival commands, the operator-motion grammar for simple edits, and the substitute command for bulk changes. Everything else is optional refinement. Learn those, practice for an hour, and vim stops being intimidating and starts being the reliable tool it is.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!