Junior 6 min · March 06, 2026

Vim Swap Corruption — The Hidden Danger of SSH Disconnects

E325 swap file warning after SSH disconnect? Recovering can write broken configs.

N
Naren · Founder
Plain-English first. Then code. Then the interview question.
About
 ● Production Incident 🔎 Debug Guide
Quick Answer
  • Vim is a modal text editor with three primary modes: Normal (commands), Insert (typing), and Command (save/quit).
  • Normal mode is the default — every key is a command, not a character. Press 'i' to type.
  • Navigation: h/j/k/l (left/down/up/right), w/b (word forward/back), gg/G (first/last line).
  • Editing: dd (delete line), yy (copy line), p (paste), u (undo). All in Normal mode.
  • Quitting: :wq (save+quit), :q! (quit discard). Enter Command mode with ':'.
  • Production insight: Most vim panics happen because you're in the wrong mode. Escape always resets to Normal mode.
Plain-English First

Imagine a Swiss Army knife where each tool only works when you flip a specific switch. That's vim — a text editor with distinct 'modes', where the same key does completely different things depending on which mode you're in. Most editors behave like a notepad: you open it and just start typing. Vim is more like a cockpit — incredibly powerful once you know the controls, but confusing until someone explains what each switch does. Once it clicks, you'll edit text faster than you ever thought possible.

Every DevOps engineer, Linux sysadmin, or backend developer will eventually find themselves staring at a vim prompt on a remote server — heart racing, fingers frozen — because it's the one editor that's guaranteed to be installed on virtually every Unix-based system on the planet. Whether you're editing a cron job at 2 AM or fixing a config file on a production server where no GUI exists, vim is the tool that's always there waiting for you.

The problem is that vim doesn't work like any editor you've used before. Press a key and instead of typing a letter, something completely unexpected happens. Try to close the window and nothing works. This isn't a bug — it's by design. Vim was built for speed and efficiency on keyboards that predate the mouse, and its modal design is the secret to that power. The confusion beginners feel is almost always because nobody explained the ONE core concept: vim has modes, and everything depends on which mode you're currently in.

By the end of this article you'll know exactly how to open and close vim without panicking, navigate a file without touching the mouse, switch between modes confidently, make real edits to text files, and save your work. You'll go from 'how do I even quit this thing?' to genuinely understanding why experienced developers swear by vim for fast, precise editing.

Vim's Three Modes — The Core Concept Everything Else Builds On

Here's the single idea that unlocks vim: it has modes. Most editors have one mode — 'typing mode'. You open the editor, you type, your words appear. Vim has three primary modes, and each one turns your keyboard into a completely different tool.

Normal Mode is where vim starts. Your keyboard acts like a remote control — every key is a command, not a letter. Press 'd' and it doesn't type the letter d; it begins a delete operation. This feels wrong at first, but it's actually brilliant: most of your time editing is not typing new text, it's navigating, deleting, copying and moving existing text. Normal mode is optimised for that.

Insert Mode is what you're used to. Here, every key types a character exactly like a standard editor. You enter Insert mode by pressing 'i' from Normal mode, do your typing, then press Escape to return to Normal mode.

Command Mode (also called Ex mode) is for file-level operations: saving a file, quitting, search-and-replace across the whole document. You enter it by pressing ':' from Normal mode.

Think of it like a car: Normal mode is when you're steering and navigating, Insert mode is when you're actually loading cargo, and Command mode is the dashboard — save trip, quit navigation, check settings. You switch lanes, not everything at once.

vim_modes_demo.shBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# ── Step 1: Open a new file called server_config.txt in vim ──
vim server_config.txt

# ── You are now in NORMAL MODE (default) ──
# Nothing you type will appear as text yet.
# The bottom of the screen shows no indicator — that means Normal Mode.

# ── Step 2: Press 'i' to enter INSERT MODE ──
# You'll see '-- INSERT --' appear at the bottom of the screen.
# Now your keystrokes type actual characters.

# ── Type this line (you're in Insert Mode now) ──
# hostname=web-server-01
# port=8080
# environment=production

# ── Step 3: Press Escape to return to NORMAL MODE ──
# The '-- INSERT --' indicator disappears.
# You are back in 'remote control' mode.

# ── Step 4: Press ':' to enter COMMAND MODE ──
# A colon ':' appears at the very bottom of the screen.
# Type 'wq' then press Enter to Write (save) and Quit.
# :wq

# ── Back in your terminal ──
# Verify the file was saved:
cat server_config.txt
Output
hostname=web-server-01
port=8080
environment=production
Watch Out:
If you start typing and see random deletions, jumps, or nothing appears — you're in Normal mode, not Insert mode. Always check the bottom of the screen. If it doesn't say '-- INSERT --', press 'i' before typing.
Production Insight
Newcomers lose production configs because they type while in Normal mode.
'dd' deletes a line silently — no undo prompt.
Rule: when in doubt, press Escape, then press 'i' to start typing.
Key Takeaway
Vim has three modes: Normal, Insert, Command.
Normal mode is for commands, Insert mode is for typing.
Escape always resets to Normal mode — your safe base.

Once you understand modes, navigation is your next superpower. In Normal mode, vim gives you precise, keyboard-driven movement that — once learned — is genuinely faster than reaching for a mouse.

The foundational movement keys are h, j, k, l — they map to left, down, up, right respectively. This sounds arbitrary, but it was intentional: these keys sit directly under your right hand's resting position on a QWERTY keyboard, so you never have to move your hand to navigate.

But letter-by-letter movement is slow. Here's where vim starts to feel magical. 'w' jumps forward one word at a time. 'b' jumps backward one word. '0' (zero) jumps to the absolute start of the current line. '$' jumps to the end of the current line. 'gg' teleports you to the very first line of the file. 'G' (capital G) teleports you to the very last line.

You can also combine numbers with movements. '5j' moves down 5 lines. '3w' jumps forward 3 words. This number-plus-command pattern is a core vim concept called a motion multiplier — it's what makes experienced vim users look like they're casting spells.

For searching, press '/' in Normal mode, type your search term, and press Enter. Vim highlights all matches and jumps to the first one. Press 'n' to jump to the next match, 'N' to go backward.

vim_navigation_demo.shBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# ── Create a sample file to practice navigation on ──
cat > deployment_notes.txt << 'EOF'
Step 1: Pull the latest Docker image
Step 2: Stop the running container
Step 3: Remove the old container
Step 4: Start the new container with updated env vars
Step 5: Run health check on port 8080
Step 6: Tail the application logs
Step 7: Confirm deployment is successful
EOF

# ── Open the file in vim ──
vim deployment_notes.txt

# ── You are in NORMAL MODE ──

# Move down 3 lines:
# Press: 3j
# Cursor is now on 'Step 4: Start the new container...'

# Jump to the end of the current line:
# Press: $
# Cursor is now on the 's' of 'vars'

# Jump to the start of the current line:
# Press: 0
# Cursor is now on 'S' of 'Step 4'

# Jump forward 2 words:
# Press: 2w
# Cursor is now on 'the'

# Jump to the last line of the file:
# Press: G
# Cursor is now on 'Step 7: Confirm deployment is successful'

# Jump back to the very first line:
# Press: gg
# Cursor is now on 'Step 1: Pull the latest Docker image'

# Search for 'health':
# Press: /health  then Enter
# Vim jumps to 'Step 5: Run health check on port 8080'
# Press 'n' to find the next occurrence (none here, it wraps)

# Exit without making changes:
# Press: :q  then Enter
Output
# (vim opens the file in your terminal)
# Navigation happens visually inside the vim editor.
# After :q, you return to your terminal prompt with no changes saved.
Pro Tip:
Run 'vimtutor' in your terminal right now. It's a built-in interactive tutorial that ships with vim and takes about 30 minutes. It's the single best way to burn h/j/k/l navigation into muscle memory — no setup required.
Production Insight
On a 500-line config file, arrow keys add ~2 seconds per move — that's a minute for 30 moves.
With h/j/k/l and numbers, the same navigation takes under 5 seconds.
Rule: force yourself to use h/j/k/l for a week. It pays for itself in hours.
Key Takeaway
Navigation in Normal mode uses h/j/k/l (left/down/up/right).
Combine with numbers: '5j' moves 5 lines down.
Search with '/term', then 'n' for next match.

Editing Text in Vim — Deleting, Copying, Pasting and Undoing

This is where vim stops feeling like a weird editor and starts feeling like a superpower. All editing commands work in Normal mode, which means you never have to click-and-drag to select text or reach for a menu. Everything is a keyboard shortcut.

Deleting: The 'd' key is your delete tool. But 'd' alone does nothing — it waits for a motion. 'dw' deletes from the cursor to the end of the current word. 'd$' deletes from the cursor to the end of the line. 'dd' (press d twice) deletes the entire current line. '3dd' deletes 3 lines at once.

Copying (Yanking): Vim calls copying 'yanking'. The 'y' key works exactly like 'd' but copies instead of cuts. 'yy' yanks the entire current line. 'yw' yanks one word.

Pasting: Press 'p' (lowercase) to paste after the cursor. Press 'P' (uppercase) to paste before the cursor. After a 'dd' or 'yy', the content lives in vim's internal clipboard.

Undoing and Redoing: Press 'u' in Normal mode to undo the last action. Press 'Ctrl + r' to redo it. Vim has a deep undo history — keep pressing 'u' to step back through multiple changes.

Changing text in place: The 'c' key is like 'd' but drops you into Insert mode after deleting. 'cw' deletes the current word and immediately lets you type a replacement. It's the fastest way to replace a word.

vim_editing_demo.shBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# ── Create a file with intentional errors to fix ──
cat > nginx_config_draft.txt << 'EOF'
server {
    lsten 80;          # typo: should be 'listen'
    server_name example.com;
    root /var/www/html;
    index index.html index.htm;
    location / {
        try_files $uri $uri/ =404;
    }
    # TODO: remove this debug line
    error_log /var/log/nginx/debug.log debug;
}
EOF

# ── Open the file ──
vim nginx_config_draft.txt

# ── FIX 1: Correct 'lsten' to 'listen' ──
# Navigate to line 2 with: 2G
# Move cursor onto 'lsten' with: w  (jump one word)
# Delete the word with: dw
# Enter Insert mode with: i
# Type: listen
# Press Escape to return to Normal mode

# ── FIX 2: Delete the entire '# TODO: remove this debug line' line ──
# Search for it: /TODO  then Enter
# Delete that whole line: dd

# ── FIX 3: Also delete the error_log line below it ──
# Cursor should now be on the error_log line (dd moves cursor down)
# Delete it: dd

# ── Undo the last deletion if you made a mistake ──
# Press: u
# The error_log line comes back

# ── Save the file and quit ──
# Press: :wq  then Enter

# ── Verify the result ──
cat nginx_config_draft.txt
Output
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
Interview Gold:
Interviewers love asking 'what's the difference between d and c in vim?' The answer: both delete, but 'c' (change) immediately drops you into Insert mode so you can type a replacement. 'd' leaves you in Normal mode. Same deletion, different workflow intent.
Production Insight
Accidentally deleting a line with 'dd' is the #1 vim panic event.
Hit 'u' immediately to undo. vim's undo history goes hundreds of steps back.
Rule: 'u' = undo, Ctrl+r = redo. Memorise these before any editing command.
Key Takeaway
dd deletes a line, yy copies a line, p pastes after cursor.
u undoes the last action, Ctrl+r redoes it.
cw deletes a word and enters Insert mode to replace it.

Saving, Quitting and the Commands You'll Use Every Single Day

The most Googled vim question of all time is 'how do I exit vim'. It's even a running joke in developer culture. The reason it trips people up is that quitting is a Command mode operation, and most newcomers get stuck because they're in the wrong mode and don't know it.

Here's the complete map of save/quit commands. Enter Command mode first by pressing ':' in Normal mode, then type the command:

':w' — Write (save) the file but stay in vim. Use this habitually as you work. ':q' — Quit vim. Only works if you haven't made unsaved changes. ':wq' — Write and quit in one step. This is your main exit command. ':q!' — Quit WITHOUT saving. The '!' forces it, discarding all changes. Use when you want to abandon edits. ':w filename.txt' — Save as a new filename (like 'Save As').

':%s/old_word/new_word/g' — Find and replace. The '%' means 'whole file', 's' means substitute, 'g' means all occurrences on each line. This is the sed command, but live inside your file.

':set number' — Show line numbers. Incredibly useful when debugging config files or referencing error line numbers from logs.

':syntax on' — Enable syntax highlighting if it isn't already active.

vim_save_quit_commands.shBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# ── Scenario: You're editing a Dockerfile on a production server ──
vim Dockerfile

# ── You make some edits (in Insert mode), then press Escape ──

# COMMAND: Save progress mid-edit without closing vim
# Press: :w  then Enter
# Output at bottom: 'Dockerfile' 12L, 310B written

# COMMAND: Enable line numbers to cross-reference an error log
# Press: :set number  then Enter
# Line numbers now appear on the left side of every line

# COMMAND: Replace every instance of 'node:14' with 'node:20'
# Press: :%s/node:14/node:20/g  then Enter
# Output at bottom: 4 substitutions on 4 lines

# COMMAND: Save the updated file to a backup copy first
# Press: :w Dockerfile.backup  then Enter
# Output: 'Dockerfile.backup' 12L, 318B written
# (vim stays open on the original Dockerfile)

# COMMAND: Save the original and quit vim
# Press: :wq  then Enter
# (back in terminal)

# ── Scenario: You open a file, realise you shouldn't change it ──
vim /etc/hosts

# You accidentally make a change (press 'i', type something, press Escape)
# COMMAND: Discard ALL changes and quit — do NOT save
# Press: :q!  then Enter
# (back in terminal — /etc/hosts is completely unchanged)

# Confirm the file is unchanged:
stat /etc/hosts
Output
# After :wq on Dockerfile:
# (returns to terminal prompt)
# After :q! on /etc/hosts:
# (returns to terminal prompt)
# stat /etc/hosts output:
File: /etc/hosts
Size: 221 Blocks: 8 IO Block: 4096 regular file
Device: fd01h/64769d Inode: 655375 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
# Timestamps unchanged — confirms no write occurred
Pro Tip:
If vim ever shows 'E45: readonly option is set (add ! to override)' when you try to save, it means the file has read-only permissions. You can force-write with ':w!' if you have sudo privileges — or use ':wq!' to force-save and quit in one shot. On system config files, run 'sudo vim filename' from the start to avoid this entirely.
Production Insight
Editing a file without write permission is common on production servers.
You edit, then :w fails — now you can't save or quit without losing work.
Rule: always use 'sudo vim filename' when editing system configs.
Key Takeaway
:w saves, :q quits (if no changes), :wq saves and quits.
:q! discards all changes and quits — your panic exit.
:%s/old/new/g replaces all occurrences in the file.

Visual Mode and Advanced Editing Techniques

Beyond basic editing, vim offers Visual mode for selecting text by character, line, or block. This is how you perform operations on a sub-section of text without typing coordinates.

Press 'v' in Normal mode to enter Visual mode character-wise. Move the cursor to expand the selection. Then press 'd' to delete, 'y' to yank, 'c' to change, or '>' to indent. Press 'V' for line-wise visual mode (selects whole lines). Press 'Ctrl+v' for block-wise visual mode — useful for editing columns of data, like adding a comment prefix to multiple lines.

Advanced actions: - '.': Repeat the last change. Incredibly powerful for repetitive edits. - '>>' and '<<': Indent/outdent the current line. - '==': Auto-indent the current line based on file type. - '~': Toggle case of the character under the cursor. - 'J': Join the current line with the line below. - 'Ctrl+a' and 'Ctrl+x': Increment/decrement the number under the cursor (e.g., change 'port 8080' to 'port 8081').

Working with multiple files: - ':e filename' — Open another file in the same vim session. - ':bnext' or ':bn' — Switch to the next buffer (open file). - ':ls' — List all open buffers. - ':bd' — Close the current buffer (file).

vim_visual_mode.shBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# ── Create a sample file ──
cat > config_block.txt << 'EOF'
server {
    listen 80;
    server_name example.com;
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
EOF

# ── Open in vim ──
vim config_block.txt

# ── Select and indent the location block ──
# Move cursor to line starting with 'location'
# Press V (line-wise visual mode) — highlights whole line
# Press j twice to highlight 3 lines (location, proxy_pass, proxy_set_header lines)
# Press > to indent the entire block one level to the right
# Press Escape to leave Visual mode

# ── Replace 'proxy_pass' in a visual selection ──
# Position cursor on 'proxy_pass' line
# Press v (character-wise visual mode)
# Move to the end of the word 'proxy_pass' with e
# Press c to change (delete selected and enter Insert mode)
# Type: backend_pass
# Press Escape

# ── Save the file ──
:w

# ── Now open another file in the same session ──
# :e /etc/hostname
# :bn to switch back to config_block.txt
# :q to quit the second file

# ── Quit vim ──
:q
Output
# After visual mode operations:
# The location block is indented one more level.
# 'proxy_pass' changed to 'backend_pass'.
The Vim Way
  • d + w = delete word (verb + motion)
  • c + $ = change to end of line
  • y + t( = yank everything until next '(' (include? no)
  • v + j + ~ = visual select down, then toggle case
  • The '.' repeats the last verb-noun combo — instant macro
Production Insight
Visual mode with Ctrl+v (block) is the fastest way to comment out a block of code.
Select lines, press I, type '#', press Escape — all lines get the prefix.
Rule: don't manually insert comment markers — use block Visual mode.
Key Takeaway
Visual mode: 'v' for character, 'V' for line, Ctrl+v for block.
Repeat last edit with '.' — saves countless keystrokes.
Open multiple files with ':e filename', switch with ':bn'.
● Production incidentPOST-MORTEMseverity: high

Swap File Corruption After SSH Disconnect

Symptom
When re-opening a file, vim displays: 'E325: ATTENTION — Found a swap file by the name .../.filename.swp' and offers options like [O]pen Read-Only, [R]ecover, [D]elete it, [Q]uit, [A]bort.
Assumption
The engineer assumed that pressing 'R' (Recover) would restore the last saved version from the swap file, which would be safe to continue editing. In reality, the swap file captures unsaved changes — which might include half-written config lines that are syntactically invalid.
Root cause
When SSH disconnected, vim was in Insert mode with partial edits. The swap file saved only the current buffer state — including a broken config line. 'Recover' loads that incomplete buffer, and the subsequent :wq writes the broken file to disk, corrupting the actual nginx.conf.
Fix
After reconnect, use the [D]elete it option to remove the swap file (it contains no useful recovery data if you can re-edit). Then re-open the file fresh. If you must recover, visually inspect the recovered content before saving — use :q! to discard it if it looks wrong.
Key lesson
  • Always use :w frequently when editing production configs — every explicit save writes a clean checkpoint.
  • The swap file is a snapshot of your in-progress edits — it can contain incomplete, broken content.
  • If you get disconnected, delete the swap file and start over unless you're sure the last saved version is acceptable.
  • To avoid swap files entirely, set 'nobackup' and 'noswapfile' in your .vimrc — but only if you trust your :w habit.
Production debug guideQuick symptom-to-action reference for vim problems during critical edits4 entries
Symptom · 01
You type keys and vim deletes lines, inserts weird characters, or jumps around.
Fix
You're in Normal mode, not Insert mode. Press Escape to reset, then press 'i' to enter Insert mode before typing.
Symptom · 02
vim shows 'E45: readonly option is set (add ! to override)' when trying to save.
Fix
You don't have write permission. Use :w! if you have sudo privileges (rarely works without sudo). Better: exit with :q! and re-open with 'sudo vim filename'.
Symptom · 03
Swap file warning on re-opening a file after SSH disconnect.
Fix
If you don't need recovery, press 'D' to delete the swap file. If you suspect unsaved work, recover with 'R', inspect, then save only if correct.
Symptom · 04
You press Ctrl+C to copy text but nothing happens.
Fix
vim doesn't use Ctrl+C for copy. In Normal mode, use 'yy' to yank (copy) a line, 'yw' to yank a word. To paste, use 'p'. For system clipboard, check if vim was compiled with clipboard support (:echo has('clipboard')) — if not, use Ctrl+Shift+V in SSH terminal.
★ Vim Quick Debug Cheat SheetFive-second fixes for the most common vim emergencies — keep this open while you learn.
Typing produces strange behaviour instead of text
Immediate action
Press Escape to return to Normal mode
Commands
Press 'i' to enter Insert mode
Type your text
Fix now
Always check bottom of screen for '-- INSERT --' indicator
Can't exit vim+
Immediate action
Press Escape a few times to ensure you're in Normal mode
Commands
Type :q! and press Enter (quit without saving)
Or :wq to save and quit
Fix now
If nothing works, close the terminal — but that leaves a swap file
Unsaved changes lost after SSH disconnect+
Immediate action
Reconnect and re-open the file
Commands
When prompted about swap file, press 'D' to delete it
Re-edit the file from scratch
Fix now
Prevent: hit :w every few minutes during critical edits
Search highlights won't go away+
Immediate action
Type :nohlsearch and press Enter
Commands
Or just :noh (short form)
To turn off search highlighting permanently, add 'set nohlsearch' to .vimrc
Fix now
Don't panic — it's just visual clutter, not a bug
Vim vs Normal Editors
ActionNormal Editor (nano/gedit)Vim Command
Open a filenano filename.txtvim filename.txt
Start typing textJust type immediatelyPress 'i' first, then type
Save the fileCtrl + S:w (Command mode)
Save and closeCtrl + X, then Y:wq
Close without savingCtrl + X, then N:q!
Delete a whole lineSelect + Backspacedd (Normal mode)
Copy a lineCtrl + Cyy (Normal mode)
PasteCtrl + Vp (Normal mode)
Undo last actionCtrl + Zu (Normal mode)
Find and replace allUsually a menu option:%s/old/new/g
Jump to last lineCtrl + EndG (Normal mode)
Jump to first lineCtrl + Homegg (Normal mode)
Show line numbersUsually default on:set number

Key takeaways

1
Vim has three modes
Normal (navigate and command), Insert (type text), Command (file operations like save and quit). Everything in vim depends on which mode you're in. When lost, press Escape to reset to Normal mode.
2
':wq' saves and quits, ':q!' quits without saving and discards all changes
these two commands will handle 90% of your real-world vim sessions on servers.
3
The 'dd' / 'yy' / 'p' trio (delete line / copy line / paste) combined with 'u' for undo is your core editing toolkit in Normal mode
faster than any mouse-driven editor once it's in muscle memory.
4
Run 'vimtutor' in any terminal to get a built-in interactive 30-minute lesson. It's the fastest legitimate way to get comfortable, and it works on any Unix system with vim installed
no internet required.
5
Visual mode (v/V/Ctrl+v) lets you select and operate on blocks of text. Use '.' to repeat the last edit
this is the 'vim macro' pattern that makes editing lightning fast.

Common mistakes to avoid

3 patterns
×

Typing text while in Normal mode

Symptom
Keys trigger unexpected commands — cursor jumps around, lines get deleted, nothing you type appears as actual characters.
Fix
Always check the very bottom of the vim window. If it doesn't say '-- INSERT --', press 'i' to enter Insert mode before you type. When in doubt, press Escape first to reset to Normal mode, then press 'i'.
×

Trying to quit with Ctrl+C or clicking the X button

Symptom
Ctrl+C does nothing useful, or if you're in an SSH session the connection might drop but vim leaves a swap file behind.
Fix
Always quit vim through Command mode. Press Escape to ensure you're in Normal mode, then type ':q!' to quit without saving, or ':wq' to save and quit. If you see a message about a swap file next time you open the file, press 'D' to delete it.
×

Running a find-and-replace like ':%s/old/new' without the trailing '/g' flag

Symptom
Only the FIRST occurrence on each line gets replaced. If a line has 'node node node', only the first 'node' changes.
Fix
Always append '/g' to replace all occurrences: ':%s/old/new/g'. Add '/gc' if you want vim to ask for confirmation before each substitution — useful on large files where you don't want to accidentally replace something you didn't intend to.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
You're SSH'd into a production Linux server and need to edit /etc/nginx/...
Q02SENIOR
What is the difference between ':q', ':q!', and ':wq' in vim? When would...
Q03JUNIOR
A junior engineer accidentally ran 'vim /etc/hosts', typed some garbage ...
Q01 of 03JUNIOR

You're SSH'd into a production Linux server and need to edit /etc/nginx/nginx.conf. There's no nano or GUI editor available. Walk me through exactly how you'd open the file, make a change, and save it safely using vim.

ANSWER
First, open with sudo: 'sudo vim /etc/nginx/nginx.conf'. Navigate to the relevant line using search '/' or 'gg'. Press 'i' to enter Insert mode, make the change. Press Escape to return to Normal mode. Save with ':w'. If the change is correct, quit with ':wq'. Always test with 'nginx -t' after saving before reloading.
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
How do I exit vim without saving changes?
02
What does '-- INSERT --' mean at the bottom of vim?
03
Is vim the same as vi? Should I learn vim or vi?
04
How do I search and replace in vim?
05
What is a swap file in vim and should I worry about it?
🔥

That's Linux. Mark it forged?

6 min read · try the examples if you haven't

Previous
SSH and SCP Explained
10 / 12 · Linux
Next
Linux System Performance Tuning