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.
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]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/gThis example will substitute all instances of foo with bar between lines 3 and 5.
:.,$s/foo/bar/gThis 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/gThis example will look at the current line and the next ten lines to replace all instances of foo with bar.
:%s/foo/bar/gThe % will look at all lines in the document.
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/giThis will detect instances of mum anywhere, including in chrysanthemum, so it’d be turned into chrysanthedad - which is likely not desired.
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/giNow chrysanthemum is safe!
This is what Vim will substitute any matches with.
There are three flags:
i)g)c):s/foo/bar/iWith the i flag for case insensitivity, Vim will match on Foo, FOo, FOO, etc.
:s/foo/bar/gWith the g flag, we will find all of the instances of foo in the range and replace them with bar.
This interactive menu can be controlled with a few keys:
y to replace the current matchn to skip the current matchl to replace the current match and quitq to quita to substitute the current match and all subsequent remaining matchesThe 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!