Search and Replace in Vim

2024-11-29

Search and replace in Vim uses the :s command to quickly substitute text in a line, range, or entire file. With options like global replacement, word boundaries, and confirmation prompts, it streamlines editing tasks efficiently.

In Vim, you can perform a search and replace using the :s (substitute) command. Here are a few common ways to do it:

  1. Replace in the current line:

    :s/old_text/new_text/g
    
    • old_text: the text you want to replace.
    • new_text: the text you want to replace it with.
    • g: makes the substitution "global" for all occurrences in the line. Without it, only the first occurrence will be replaced.
  2. Replace in the entire file:

    :%s/old_text/new_text/g
    
    • %: applies the command to every line in the file.
  3. Replace in a specific range of lines:

    :5,10s/old_text/new_text/g
    
    • 5,10: applies the command to lines 5 through 10.
  4. Confirm each replacement:

    :%s/old_text/new_text/gc
    
    • c: asks for confirmation before each replacement. Type y for "yes," n for "no," a for "all," or q to quit.
  5. Replace only whole words:

    :%s/\<old_text\>/new_text/g
    
    • \< and \> match the beginning and end of a word boundary.

This flexibility allows for very precise control over replacements in Vim.