created December 24, 2001 · complexity basic · author Anon · version 5.7
Did you know that with Vim you can search for more than one word with a single command. Say you want to search all occurrences of "bill" or "ted" or "harry" in a text.
In normal mode do the following:
/\(bill\)\|\(ted\)\|\(harry\) <Enter>
This will match all instances of either "bill", or "ted", or "harry" in your text.
\(\) group characters in a word (not needed above) \| is OR
To replace all instances of "bill" or "ted" or "harry" with "greg" do the following:
:%s/\(bill\)\|\(ted\)\|\(harry\)/greg/g <enter>
Note: If you have set the option "gdefault" you don't need the "g" at the end of the above command.
Comments
1) Simplified Search If you don't want to do replaces with captured text you can simplify eliminating the escaped parentheses, thus
/\(bill\)\|\(ted\)\|\(harry\) <Enter>
becomes
/bill\|ted\|harry <Enter>
Note that you do still have to escape the pipe symbol
2) Simplified Replace In the example given you don't need the escaped parens to replace the text 'bill' 'ted' or 'harry' with the word 'greg,' thus
:%s/\(bill\)\|\(ted\)\|\(harry\)/greg/g <enter>
becomes
:%s/bill\|ted\|harry/greg/g <enter>
3) Capturing the enclosed text If you do want to capture the enclosed text for replacement it's still simpler to enclose the whole statement in one set of parens, thus
/\(bill\)\|\(ted\)\|\(harry\) <Enter>
becomes
/\(bill\|ted\|harry\) <Enter>
4) The full monty Since using escaped parens -- as in \(bill\|...\) -- captures the enclosed text in a regex \1 variable you can do replacements that would otherwise be sick and wrong, like put every instance of 'bill' 'ted' or 'harry' in quotes, thus
:%s/\(bill\|ted\|harry\)/"\1"/g
If you are using the entire matched text as part of your replace pattern, it is easier to use & instead of enclosing the entire search pattern in \( ...\) and referencing it as \1. Using this, the following substitute command:
:%s/\(bill\|ted\|harry\)/"\1"/g
can be simplified to this:
:%s/bill\|ted\|harry/"&"/g
The & will be replaced with the entire matching text.