How do I delete text from the cursor to the next occurrence of a pattern?
Answer
d/{pattern}<CR>
Explanation
Vim lets you use a / search as a motion for any operator. d/pattern<CR> deletes from the current cursor position up to (but not including) the next match of pattern. This is faster than visually selecting the region or relying on word-level motions when the target boundary is best described as a pattern.
How it works
d— the delete operator/pattern<CR>— a forward search motion; Vim deletes from the cursor position to the start of the match
The deleted text is placed in the unnamed register and can be pasted with p. The match itself is not deleted — only the text up to it.
You can use any operator this way: c/pattern<CR> changes text, y/pattern<CR> yanks it, v/pattern<CR> selects it visually.
Example
Given:
return calculateTotal(items, tax, discount);
With cursor on c in calculateTotal, typing d/)<CR> deletes up to the first ):
return );
Tips
- Use
d?pattern<CR>to delete backwards to the previous match - The search motion is exclusive by default — the character at the match position is not deleted. Append
\/eoffset to make it inclusive:d/pattern\/e<CR> - After the delete, the search pattern is set to
pattern, sonwill jump to the next occurrence - Pair with
cgnfor a more targeted approach:/pattern<CR>cgnchanges the first match, then.can change subsequent ones - Works with counts:
2d/pattern<CR>deletes up to the second occurrence