Tip 89Find and Replace Every Match in a File

By default, the substitute command acts on the current line, changing the first occurrence only. To change every match throughout a file, we have to specify a range and use the g flag.

For demonstration purposes, we’ll use this text:

 When the going gets tough, the tough get going.
 If you are going through hell, keep going.

Let’s try and replace every occurrence of the word going with rolling. First, we’ll enable the ‘hlsearch’ option so that we can see what we’re doing (see Tip 81, for more details):

=> :set hlsearch

The simplest thing that we could do with the substitute command is to provide a target {pattern} and replacement {string}:

KeystrokesBuffer Contents ...

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.