In Vim, you can perform substitutions using the :s command, which stands for “substitute”. The basic syntax of the :s command is:

:s/pattern/replacement/flags

Where:

  • pattern is the text you want to search for.
  • replacement is the text you want to replace pattern with.
  • flags are optional and can modify how the substitution is performed.

Here’s how you can use the :s command in Vim:

  1. Simple substitution: To substitute the first occurrence of “old” with “new” in the current line:

    :s/old/new/
    
  2. Substitution with flags:

    • g: Global flag, replaces all occurrences in the line.
    • c: Confirm flag, asks for confirmation before replacing each occurrence.
    • i: Case-insensitive flag, makes the search case-insensitive.
    • I: Case-sensitive flag, makes the search case-sensitive.
    • &: Repeats the last substitution.

    Example:

    :s/old/new/g
    
  3. Substitution in a range: To substitute “old” with “new” in lines 5 to 10:

    :5,10s/old/new/
    
  4. Substitution in the entire file: To substitute “old” with “new” in the entire file:

    :%s/old/new/g
    
  5. Substitution with confirmation: To replace all occurrences of “old” with “new” with confirmation:

    :%s/old/new/gc
    
  6. Substitution with backreferences: You can use \1, \2, etc., in the replacement string to insert text matched by capturing groups in the pattern. Example:

    :s/\(first\)\s+\(last\)/\2, \1/
    
  7. Substitution using regular expressions: Vim supports powerful regular expressions for pattern matching. Be sure to escape special characters if you want them to be treated literally.

Remember, after typing :s, you can press the up arrow key to recall previous substitution commands, making it easy to reuse them.