Search and replace

Vim supports search and replace through the :substitute command, most often abbreviated to :s. By default, :s will replace one substring with another in a current line. It has the following format:

:s/<find-this>/<replace-with-this>/<flags>

The flags are optional, and you shouldn't worry about them for now. To try it, open animal_farm.py, navigate to the line containing cat (for example, with /cat), and execute the following:

:s/cat/dog

As you can see in the screenshot, this replaces the first occurrence of cat in the current line:

Now, let's look at the flags you can pass to the substitute command:

  • g—global replace: replace ...

Get Mastering Vim 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.