Vim Search and Replace

Substitute expression (magic)

- -
& * * \0
\1\9 Replace with the group 0-9
\u Uppercase next letter
\U Uppercase following characters
\l Lowercase next letter
\L Lowercase following characters
\e End of \u, \U, \l and \L
\E End of \u, \U, \l and \L

Flags

- -
g Replace all occurrences
i Ignore case
I Don't ignore case
c Confirm each substitution

Inverse :g

:[range]v/{pattern}/[command]

:v/foo/d Delete lines not containing foo(also :g!/foo/d)

Global command

:[range]g/{pattern}/[command]

:g/foo/d Delete lines containing foo
:g!/foo/d Delete lines not containing foo
:g/^\s*$/d Delete all blank lines
:g/foo/t$ Copy lines containing foo to EOF
:g/foo/m$ Move lines containing foo to EOF
:g/^/m0 Reverse a file
:g/^/t. Duplicate every line

Ranges

- -
% Entire file
’<,’> Current selection
5 Line 5
5,10 Lines 5 to 10
$ Last line
2,$ Lines 2 to Last
. Current line
,3 Next 3 lines
-3, Forward 3 lines

Replace FILE

:%s/{pattern}/{str}/[flags]

:%s/old/new Replace first
:%s/old/new/g Replace all
:%s/old/new/gc Replace all (Confirm)
:%s/old/new/gi Replace all (ignore case)
:%s/\vold/new/g Replace all with regex

Replace LINE

:[range]s/{pattern}/{str}/[flags]

:s/old/new Replace first
:s/old/new/g Replace all
:s/\vold/new/g Replace all with regex
:s/old/new/gc replace all (Confirm)
:s/old/new/i Ignore case replace first
:2,6s/old/new/g Replace between lines 2-6

Search

- -
/foo Search forward
/foo\c Search forward (case insensitive)
?foo Search backward
/\v\d+ Search with regex
n Next matching search pattern
N Previous match
* Search for current word forward
# Search for current word backward
Comments