In the Vi text editor, you can replace characters, words, or even patterns using a variety of commands. Here are some of the top commands for replacing characters in Vi.

Vi editor replace
Photo by Skylar Kang on Pexels.com

Vi Editor: Here are commands to replace Character(s)

  1. Replace Single Character at Cursor Position:
    • r followed by the character you want to replace the current character with. For example, to replace the character under the cursor with ‘X’, press rx.
  2. Replace Multiple Characters:
    • R (capital ‘R’) puts Vi into replace mode. You can then type over existing characters, and they will be replaced one by one as you type.
  3. Replace All Occurrences of a Character in a Line:
    • :s/old/new/g – This command replaces all occurrences of ‘old’ with ‘new’ in the current line. Replace ‘old’ and ‘new’ with your desired characters.
  4. Replace All Occurrences of a Character in the Entire File:
    • :%s/old/new/g – This command replaces all occurrences of ‘old’ with ‘new’ throughout the entire file.
  5. Replace a Specific Word:
    • :s/old/new/g – Replace ‘old’ with ‘new’ in the current line. To replace only the first occurrence in each line, omit the ‘g’ flag.
  6. Replace a Specific Pattern:
    • You can use regular expressions with the :s command to replace patterns. For example, to replace all occurrences of ‘apple’ with ‘banana’, use :%s/apple/banana/g.
  7. Replace Within a Range of Lines:
    • To replace within a specific range of lines, specify the range before the :s command. For example, to replace ‘old’ with ‘new’ in lines 5 to 10, use :5,10s/old/new/g.
  8. Confirm Replacements:
    • To confirm each replacement, add the ‘c’ flag to the :s command. For example, :%s/old/new/gc will prompt you to confirm each replacement.
  9. Replace in Visual Mode:
    • Enter Visual mode by pressing v, select the text you want to replace, and then press : to enter command-line mode. You can then use s/old/new/g to replace the selected text.
  10. Global Replace (Without Confirmation):
    • To replace all occurrences of a character globally without confirmation, you can use the :g command. For example, :%s/old/new/g will replace ‘old’ with ‘new’ on all lines, and :g/old/s//new/g will do the same but without confirmation.

Remember that Vi operates in different modes (normal, insert, and command line), so you may need to switch between these modes appropriately when using these commands. To save your changes after making replacements, press Esc to enter normal mode and then use the :wq command to save and quit or :w to save the changes without quitting.

Related