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: Here are commands to replace Character(s)
- Replace Single Character at Cursor Position:
rfollowed by the character you want to replace the current character with. For example, to replace the character under the cursor with ‘X’, pressrx.
- 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.
- 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.
- 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.
- 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.
- Replace a Specific Pattern:
- You can use regular expressions with the
:scommand to replace patterns. For example, to replace all occurrences of ‘apple’ with ‘banana’, use:%s/apple/banana/g.
- You can use regular expressions with the
- Replace Within a Range of Lines:
- To replace within a specific range of lines, specify the range before the
:scommand. For example, to replace ‘old’ with ‘new’ in lines 5 to 10, use:5,10s/old/new/g.
- To replace within a specific range of lines, specify the range before the
- Confirm Replacements:
- To confirm each replacement, add the ‘c’ flag to the
:scommand. For example,:%s/old/new/gcwill prompt you to confirm each replacement.
- To confirm each replacement, add the ‘c’ flag to the
- 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 uses/old/new/gto replace the selected text.
- Enter Visual mode by pressing
- Global Replace (Without Confirmation):
- To replace all occurrences of a character globally without confirmation, you can use the
:gcommand. For example,:%s/old/new/gwill replace ‘old’ with ‘new’ on all lines, and:g/old/s//new/gwill do the same but without confirmation.
- To replace all occurrences of a character globally without confirmation, you can use the
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







You must be logged in to post a comment.