Search and Replace
Typical Syntax
- :%s/SEARCH/REPLACEMENT/g
- % - tells vim to search the entire file
- g - tells vim to replace all instances on each line, instead of just the first
Metacharacters
. | any character except new line |
\s | whitespace character |
\S | non-whitespace character |
\d | digit |
\D | non-digit |
\x | hex digit |
\X | non-hex digit |
\o | octal digit |
\O | non-octal digit |
\h | head of word character (a,b,c…z,A,B,C…Z and _) |
\H | non-head of word character |
\p | printable character |
\P | like \p, but excluding digits |
\w | word character |
\W | non-word character |
\a | alphabetic character |
\A | non-alphabetic character |
\l | lowercase character |
\L | non-lowercase character |
\u | uppercase character |
\U | non-uppercase character |
clear search highlighting
- :let @/=''
Newline Replace
- using \n as a replacement will NOT break the lines as expected (\n can be used as the search pattern)
- instead, type :%s/SEARCH/
- at this point, press CTRL-V, Enter (you should now see :%s/SEARCH/^M
- finish your pattern: :%s/SEARCH/^M/g (all SEARCH occurrences will be replaced with newlines, and lines WILL break)
- tab can also be accomplished the same way, but \t works anyway
- when using gvim (Windows), CTRL-V is probably mapped to paste from the clipboard; instead, use CTRL-Q the same way
Special Characters
Search results can be replaced with special characters like this:
- type :%s/SEARCH/
- press CTRL-V (CTRL-Q on windows); you now have the option to:
- type the 3 digit decimal value for the character you want
- type x then the 2 character hex value you want
- type o then the 3 digit octal value you want
- full example to replace all occurances of SEARCH with a vertical tab:
:%s/SEARCH/ (press CTRL-V or CTRL-Q) (press the letter o) 013/g
- once the replace is done, you can move the cursor over the character and type 'ga' to see the decimal, hex, and octal values