How do I do a case-preserving search and replace in Vim?
:%s/\v(old)/\=toupper(submatch(0)[0]).tolower(submatch(0)[1:])/g
Standard substitutions don't preserve the original case of matched text.
:%s/\v(old)/\=toupper(submatch(0)[0]).tolower(submatch(0)[1:])/g
Standard substitutions don't preserve the original case of matched text.
:keeppattern %s/old/new/g
When you run a :s or :%s substitute command, Vim updates the search register (@/) with the substitution pattern.
command-line #ex-commands #search #editing #registers #substitute
/\(function\s\+\)\zs\w\+
Vim's \zs and \ze atoms let you control which part of a matched pattern gets highlighted and operated on.
/\zs and \ze
The \zs and \ze atoms let you define where the actual match starts and ends within a larger pattern.
/pattern1/;/pattern2/
Vim's search offsets allow chaining two patterns together with a semicolon.
:set iskeyword+={char}
iskeyword defines which characters are considered word characters in Vim.
:%s/\s\+/ /g
The pattern \s\+ matches one or more whitespace characters (spaces, tabs).
:'<,'>s/pattern/replacement/g
When you make a visual selection and then type :, Vim automatically inserts ' as the range — the marks for the start and end of the last visual selection.
"/p
Vim stores the last search pattern in the search register "/.
/\Cpattern
Vim's ignorecase and smartcase settings change how all searches behave globally.
:helpgrep {pattern}
:helpgrep searches the full text of every Vim help file for a pattern and loads all matches into the quickfix list.
//
In Vim, pressing // (two forward slashes) in Normal mode repeats the last search pattern.
:nohlsearch
After a search in Vim, matched text is highlighted as long as hlsearch is enabled.
:/start/,/end/s/pattern/replacement/g
You can restrict a substitution to a range defined by two patterns.
\u and \l in :s replacement
Vim's substitute command supports special case modifiers in the replacement string that let you change the case of captured text on the fly.
/\(foo\)\@<=bar
Use \@<= for positive lookbehind.
:%s/; /;\r/g
In the replacement part, use \r to insert a newline.
:%s/\d\+/\=submatch(0)*2/g
Use \= to evaluate expressions.
/\Vexact.string
Prefix with \V for very nomagic mode where almost all characters are treated literally.
<C-r>/ or q/
Press q/ to open search history in a window.