docs:vim:search_and_replace

This is an old revision of the document!


  • :%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
. 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
  • :let @/=''
  • 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

Search results can be replaced with special characters like this:

  • type :%s/SEARCH/
  • press CTRL-V (CTRL-Q on windows)
  • now type the 3 digit decimal value for the character you want
  • full example to replace all occurances of SEARCH with a vertical tab:
    :%s/SEARCH/
    (press CTRL-V or CTRL-Q)
    011/g
  • docs/vim/search_and_replace.1232648504.txt.gz
  • Last modified: 2009/01/22 11:21
  • by billh