Changing and Replacing Text in Vim: Essential Commands

  • cw (Change Word): Replaces the word under the cursor until the end of the word and places you in insert mode.
  • cc (Change Line): Deletes the content of the entire line and transitions you to insert mode.
  • c$ (Change to End of Line): Deletes from the cursor to the end of the line and enters insert mode.
  • ci" (Change Inside Quotes): Deletes text inside quotes and enters insert mode.

Replacing Text with Specific Characters

  • r (Replace a Single Character): Press r followed by the character that will replace the current character under the cursor.
  • R (Replace Mode): Enters replace mode where each typed character replaces the existing character at the cursor’s position.

Using Substitution Commands

  • :s/old/new/: Substitute ‘old’ with ’new’ for the first occurrence in the current line.
  • :s/old/new/g: Substitute ‘old’ with ’new’ globally in the current line.
  • :%s/old/new/g: Substitute ‘old’ with ’new’ throughout the entire document.

Practical Examples and Tips

  1. Changing Specific Portions of Text:

    • Use cw at the start of a word to change the entire word. If you need to change from a specific character in a word, move the cursor there first.
    • ci( is useful in coding to change everything inside parentheses.
  2. Efficient Replacement Strategies:

    • The r command is best for quick, one-off character replacements.
    • For replacing multiple characters, R can be more efficient than using i mode, as it overwrites existing text rather than inserting.
  3. Mastering Substitution:

    • Practice using the substitution commands with the g flag to make global changes within a line or file, which is particularly useful for batch edits or corrections.

Advanced Techniques

  • Visual Mode Replacement: Select text in visual mode (v or Ctrl-v for block selection), then press c to remove the selected text and enter insert mode, ready for new input.
  • Combine with Movement Commands: Enhance your editing efficiency by combining change commands with movement commands, like c3w to change the next three words.