Vim regular expressions

In this section we explain how to search for (and change) strings using pattern matching with regular expressions.

1. Searching for strings

a) In normal mode, type
/<string> <ENTER>
for example, /hello <ENTER>. Then each time you type n the cursor will be relocated to the next instance of the string "hello".

b) To search for either of {"abc","aBc"} one can type a single command:
/a[bB]c <ENTER>
where the square brackets mean "or".

c) One can search for any string in the set
{"ac", "abc", "abbc", "abbbc", ... }
using the command
/ab*c <ENTER>
where b* means "zero or more b's".

d) In order to search for a word rather than a string. For example, to search for the word "and" using
/and <ENTER>
will also find words containing "and" such as "sandy". To ensure that you only find "and" add word boundaries to the search:
/\<and\>
(Note - in this case < and > were literals, rather than defining an action as with <ENTER>)

2. Search and replace/substitute

Subsituting a string is very like a search. For example, changing every occurrence in a file of "abc" to "ABC" simply requires the command:
:%s/abc/ABC/g <ENTER>

By way of explanation:
a) : means "change to command mode"
b) %s means "substitute on every line in the file"
c) /g means "replace all occurrences in the line - not just the first."

References

The first in this list is a well written article covering quite a lot without too much pain - well worth a read!

  1. Vim tips: The basics of search and replace, Joe 'Zonker' Brockmeier, Linux.com (28 June 2006)
  2. Patterns and search commands, Vim User Manual, Bram Moolenaar (last change: 30 April 2006).
  3. Tip #31: Find and Replace, Vim Tips (created 7 March 2001).