Skip to main content

Search and Replace

Complete guide to finding and replacing text in Vim.

Search Commands

/{pattern}    " Search forward for pattern
?{pattern} " Search backward for pattern
n " Go to next match
N " Go to previous match

Search Examples

/hello        " Search for 'hello'
/Hello " Search for 'Hello' (case sensitive)
?world " Search backward for 'world'

Search Navigation

n             " Next match (same direction as last search)
N " Previous match (opposite direction)
* " Search forward for word under cursor
# " Search backward for word under cursor
g* " Search forward for partial word under cursor
g# " Search backward for partial word under cursor

Advanced Search Patterns

Word Boundaries

/\<word\>     " Search for whole word 'word'
/\<hello " Search for words beginning with 'hello'
/world\> " Search for words ending with 'world'

Line Anchors

/^hello       " Search for 'hello' at beginning of line
/world$ " Search for 'world' at end of line
/^$ " Search for empty lines
/^\s*$ " Search for blank lines (including whitespace)

Character Classes

/[abc]        " Search for 'a', 'b', or 'c'
/[a-z] " Search for any lowercase letter
/[A-Z] " Search for any uppercase letter
/[0-9] " Search for any digit
/[^abc] " Search for anything except 'a', 'b', or 'c'

Predefined Character Classes

/\d           " Search for digits [0-9]
/\D " Search for non-digits [^0-9]
/\s " Search for whitespace [ \t\n\r]
/\S " Search for non-whitespace [^ \t\n\r]
/\w " Search for word characters [a-zA-Z0-9_]
/\W " Search for non-word characters [^a-zA-Z0-9_]

Quantifiers

/colou\?r     " Search for 'color' or 'colour' (? = 0 or 1)
/go\+ " Search for 'go', 'goo', 'gooo', etc. (+ = 1 or more)
/go\* " Search for 'g', 'go', 'goo', etc. (* = 0 or more)
/go\{2,4} " Search for 'goo', 'gooo', or 'goooo' ({n,m} = n to m)
/go\{3} " Search for exactly 'gooo' ({n} = exactly n)
/go\{2,} " Search for 'goo' or more ({n,} = n or more)

Alternation

/cat\|dog     " Search for 'cat' or 'dog'
/\(red\|blue\) car " Search for 'red car' or 'blue car'

Grouping

/\(abc\)\+    " Search for 'abc', 'abcabc', 'abcabcabc', etc.
/\(hello\|hi\) world " Search for 'hello world' or 'hi world'

Search Options

Case Sensitivity

:set ignorecase     " Make searches case-insensitive
:set noignorecase " Make searches case-sensitive
:set smartcase " Case-insensitive unless uppercase used

Search Highlighting

:set hlsearch       " Highlight search results
:set nohlsearch " Don't highlight search results
:nohlsearch " Clear current search highlighting
:set incsearch      " Show matches as you type
:set noincsearch " Don't show matches as you type

Search Wrapping

:set wrapscan       " Search wraps around file
:set nowrapscan " Search doesn't wrap around file

Replace Operations

Basic Replace Syntax

:s/{pattern}/{replacement}/    " Replace first occurrence in line
:s/{pattern}/{replacement}/g " Replace all occurrences in line
:%s/{pattern}/{replacement}/ " Replace first occurrence in each line
:%s/{pattern}/{replacement}/g " Replace all occurrences in file

Replace Examples

:s/old/new/           " Replace first 'old' with 'new' in current line
:s/old/new/g " Replace all 'old' with 'new' in current line
:%s/old/new/g " Replace all 'old' with 'new' in entire file
:1,10s/old/new/g " Replace in lines 1-10

Replace Flags

g     " Replace all occurrences in line (global)
c " Confirm each replacement
i " Case-insensitive replacement
I " Case-sensitive replacement

Replace with Confirmation

:%s/old/new/gc        " Replace all with confirmation

Confirmation options:

  • y - Yes, replace this match
  • n - No, skip this match
  • a - All, replace all remaining matches
  • q - Quit, stop replacing
  • l - Last, replace this match and quit
  • ^E - Scroll up
  • ^Y - Scroll down

Range-Based Replace

:1,5s/old/new/g       " Replace in lines 1-5
:.,+5s/old/new/g " Replace in current line and next 5
:.-5,.s/old/new/g " Replace in 5 lines above through current
:'<,'>s/old/new/g " Replace in visual selection

Advanced Replace Techniques

Backreferences

:%s/\(hello\) \(world\)/\2 \1/g    " Swap 'hello world' to 'world hello'
:%s/\([a-z]\+\)/\u\1/g " Capitalize first letter of each word

Special Replacement Characters

\r    " Carriage return
\n " Newline
\t " Tab
\\ " Literal backslash
\0 " Entire matched string
\1-9 " Backreferences to captured groups

Case Conversion in Replacement

\u    " Uppercase next character
\l " Lowercase next character
\U " Uppercase rest of string
\L " Lowercase rest of string
\e " End case conversion

Replace Examples with Case Conversion

:%s/\w\+/\u&/g        " Capitalize first letter of each word
:%s/\w\+/\U&/g " Convert all words to uppercase
:%s/\w\+/\L&/g " Convert all words to lowercase

Search and Replace with Registers

/\=@a              " Search for contents of register 'a'

Using Registers in Replace

:%s/old/\=@a/g     " Replace with contents of register 'a'

Multiple File Search and Replace

:grep {pattern} {files}    " Search for pattern in files
:vimgrep {pattern} {files} " Vim's internal grep

Replace in Multiple Files

:args *.txt           " Add all .txt files to argument list
:argdo %s/old/new/g " Replace in all files in argument list
:argdo update " Save all modified files

Buffer-based Replace

:bufdo %s/old/new/g   " Replace in all open buffers
:bufdo update " Save all modified buffers

Search History

Accessing Search History

/{up arrow}     " Previous search
/{down arrow} " Next search
q/ " Open search history window

Search History Commands

:history /      " Show search history
:history ? " Show reverse search history

Practical Search and Replace Examples

Common Text Transformations

:%s/\s\+$//g           " Remove trailing whitespace
:%s/\s\+/ /g " Replace multiple spaces with single space
:%s/^\s\+//g " Remove leading whitespace
:%s/\n\n\+/\r\r/g " Replace multiple blank lines with single blank line

Programming-specific Replacements

:%s/var /let /g        " Replace 'var' with 'let' in JavaScript
:%s/\<NULL\>/null/g " Replace NULL with null
:%s/\([a-z]\)_\([a-z]\)/\1\u\2/g " Convert snake_case to camelCase

URL and Email Replacements

:%s/http:/https:/g     " Replace HTTP with HTTPS
:%s/@oldomain\.com/@newdomain.com/g " Replace email domain

Search and Replace Tips

Efficiency Tips

  1. Use / for quick searches instead of :s when just locating
  2. Use * and # to search for word under cursor
  3. Use visual selection for targeted replacements
  4. Test with single line first before doing global replace
  5. Use confirmation (c flag) for important replacements

Common Patterns

/\<\w\+\>          " Find whole words
/\d\{3}-\d\{3}-\d\{4} " Find phone numbers (XXX-XXX-XXXX)
/\w\+@\w\+\.\w\+ " Find email addresses (simple pattern)

Regular Expression Tips

  1. Use \v for very magic mode - fewer escapes needed
  2. Use \V for very literal mode - no special characters
  3. Use \c for case-insensitive and \C for case-sensitive
  4. Use \< and \> for word boundaries

Very Magic Mode Examples

/\v(cat|dog)       " Alternation without escaping
/\vword\+ " One or more without escaping
/\v<word> " Word boundaries without escaping

Troubleshooting Search and Replace

Common Issues

  1. Special characters not escaped - Use \ before ., *, +, etc.
  2. Case sensitivity problems - Check :set ignorecase and :set smartcase
  3. Regex not working - Try very magic mode with \v
  4. Replace not working globally - Add g flag to replace command

Debug Tips

:set hlsearch         " Highlight to see what's being matched
/pattern<CR>n " Test search pattern first
:s/pattern/replace/ " Test on single line first

This comprehensive guide covers all aspects of searching and replacing in Vim. Master these techniques to efficiently find and modify text in your files.