Searching and Replacing Text in Vim: A Detailed Tutorial

Basic Search Commands

  • Search Forward: Type /pattern and press Enter to search for pattern forward through the text.
  • Search Backward: Type ?pattern and press Enter to search for pattern backward.
  • Repeat Search: Press n to find the next occurrence and N to find the previous occurrence.

Basic Replace Command

  • Substitute Command: The :s command is used for substitution in Vim:
    :s/old/new/
    This command replaces the first occurrence of old with new in the current line.

Global Replacement

  • Replace All Occurrences in a Line: Append g to the substitute command:
    :s/old/new/g
  • Replace Throughout the File: Use % to denote the entire file:
    :%s/old/new/g

Using Regular Expressions

Vim’s substitution commands can be enhanced by regular expressions for more complex search patterns:

  • Case Insensitive Search: Add i after the command:
    :%s/old/new/gi
  • Using Capture Groups: Parentheses are used to create capture groups, which can be referenced in the replacement:
    :%s/\(old\) text/\1 new/g

Practical Examples and Tips

  • Refine Your Search: Use more specific patterns to avoid unwanted changes. For example, /\bold\b ensures that only the whole word old is matched.
  • Confirm Each Replacement: Add c to prompt for confirmation for each replacement:
    :%s/old/new/gc
  • Undoing Replacements: If a replacement goes wrong, press u to undo the last command.

Advanced Search and Replace Techniques

  • Using Metacharacters: Characters like . (any single character), * (zero or more of the preceding element), and [] (character class) can be used to match complex patterns.
  • Line-Specific Substitutions: Perform replacements within a range of lines:
    :10,20s/old/new/g
  • Integrating With Other Commands: Use :global to combine searching with other commands:
    :g/pattern/norm dwiNew