Learn Vim / How to Find and Replace in Specific Lines in Vim

How to Find and Replace in Specific Lines in Vim

The answerPut a line range before s: :4,6s/old/new/g replaces only on lines 4–6.

Try it on a real buffer

Only lines 4–6 should change: replace “cat” with “dog” on those lines only, using :4,6s/cat/dog/g — every other cat must survive.

line 1: the cat sat on the mat
line 2: the cat chased the yarn
line 3: the cat ignored you completely
line 4: the cat sat on the mat
line 5: the cat chased the yarn
line 6: the cat ignored you completely
line 7: the cat sat on the mat
line 8: the cat knocked a glass off the table

Canonical solution: :4,6s/cat/dog/g Enter · par: 16 keystrokes (vimgolf rules — every keypress counts).

Why it works

The part before s is a range: % is the whole file, 4,6 is lines 4 through 6, .,$ is from here to the end. Ranges work with many ex commands, not just substitute.

Variations

KeysWhat it does
:4,6s/old/new/glines 4 through 6
:.,$s/old/new/gfrom the current line to the end
:'<,'>s/old/new/gin the visual selection (auto-inserted)
:%s/old/new/gthe whole file

Reading about keystrokes doesn't build keystrokes. Try this in a real vim buffer right now — the “Surgical strike” mission takes about a minute.

Practice free — no signup →

Keep going