s: :4,6s/old/new/g replaces only on lines 4–6.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).
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.
| Keys | What it does |
|---|---|
| :4,6s/old/new/g | lines 4 through 6 |
| :.,$s/old/new/g | from the current line to the end |
| :'<,'>s/old/new/g | in the visual selection (auto-inserted) |
| :%s/old/new/g | the 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 →