Vim Tips Wiki
Advertisement
Tip 188 Printable Monobook Previous Next

created 2001 · complexity basic · version 6.0


A search pattern can use \| to search for something or something else. For example, to search for all occurrences of "red" or "green" or "blue", enter the following search pattern (in normal mode, press / then type the pattern, then press Enter):

red\|green\|blue

To replace all instances of "red" or "green" or "blue" with "purple", enter:

:%s/red\|green\|blue/purple/g

However, the above pattern finds "red" in "bored", so the substitute would change "bored" to "bopurple". If that is not what you want, use the following pattern to find only the whole words "red" or "green" or "blue":

\<\(red\|green\|blue\)\>

In a pattern, \< and \> respectively specify the beginning and end of a word, while \( and \) respectively specify the beginning and end of a group (the pattern \<red\|green\|blue\>, without escaped parentheses, would find "red" occurring at the beginning of a word, or "green" occurring anywhere, or "blue" occurring at the end of a word).

After searching with the command /\<\(red\|green\|blue\)\> you could change the whole words "red" or "green" or "blue" to "purple" by entering the following (the search pattern is empty in this command, so it uses the last search):

:%s//purple/g

In a substitute, you can use & in the replacement to mean the "whole matched pattern" (everything that was found). For example, the following will insert quotes around all occurrences of the whole words "red" and "green" and "blue":

:%s/\<\(red\|green\|blue\)\>/"&"/g

If you do not want the whole matched pattern, you can use parentheses to group text in the search pattern, and use the replacement variable \1 to specify the first group. For example, the following finds "color x" and replaces it with "colored x" where x is the whole word "red" or "green" or "blue":

:%s/color \<\(red\|green\|blue\)\>/colored \1/g

Comments

Advertisement