vim: find and replace basics with substitute

2021-11-01

 | 

~3 min read

 | 

472 words

I’m working on using Vim as a basic text editor. In order for that to work, I needed to learn how to use some basic find and replace functions.

Fortunately, there are lots of great resources on the topic, including this post on linuxize that got me started.

General Form

The Vim command that provides find and replace functionality is substitute (which can be shortened to its alias of s). It’s general form is:

:[range]s/{pattern}/{string}/[flags] [count]

Range

By default (when no range is specified), substitute will operate only on the current line. The current line is defined as where the cursor is located.

Ranges are specified using line numbers or symbols. The ranges are separated with a , or ;.

:3,5s/foo/bar/g

This example will substitute all instances of foo with bar between lines 3 and 5.

:.,$s/foo/bar/g

This example will substitute all instances of foo with bar between the current line (.) and the end of the document ($).

There’s also the + and - which, when accompanied by a number, will provide a relative range. For example:

:.,+10s/foo/bar/g

This example will look at the current line and the next ten lines to replace all instances of foo with bar.

:%s/foo/bar/g

The % will look at all lines in the document.

Pattern

The pattern is what Vim will detect matches on. It can be either a string or a regular expression.

By default, Vim will look for the pattern within a word, e.g.,

:s/mum/mom/gi

This will detect instances of mum anywhere, including in chrysanthemum, so it’d be turned into chrysanthedad - which is likely not desired.

Whole Word Substitution

To solve the “problem” of finding our patterns within a word, we can use the symbols \< and \> to indicate the beginning and end of the word respectively.

Using our example from before, this would look like

:s/\<mum\>/mom/gi

Now chrysanthemum is safe!

String

This is what Vim will substitute any matches with.

Flags

There are three flags:

  • case insensitivity (i)
  • global search (g)
  • confirm replacements (c)

Case Insensitivity

:s/foo/bar/i

With the i flag for case insensitivity, Vim will match on Foo, FOo, FOO, etc.

:s/foo/bar/g

With the g flag, we will find all of the instances of foo in the range and replace them with bar.

Confirm Replacements

This interactive menu can be controlled with a few keys:

  • y to replace the current match
  • n to skip the current match
  • l to replace the current match and quit
  • q to quit
  • a to substitute the current match and all subsequent remaining matches

Count

The count is a positive integer that will multiply the command.



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!