Tip 91Reuse the Last Search Pattern

Leaving the search field of the substitute command blank instructs Vim to reuse the most recent search pattern. We can exploit this fact to streamline our workflow.

Let’s face it: to execute a substitute command, we have to do a lot of typing. First we specify the range, then we fill out the pattern and replacement fields, and finally we append any necessary flags. That’s a lot to think about, and making a mistake in any of these fields could change the outcome.

Here’s the good news: leaving the search field blank tells Vim to use the current pattern.

Take this monolithic substitute command (from Tip 85):

=> :%s/\v'(([^']|'\w)+)'/“\1”/g

It’s equivalent to these two separate commands:

=> /\v'(([^']|'\w)+)' ...

Get Practical Vim, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.