Vim
Replace
In Vim editor, you can replace strings using the :s command, which stands for substitute. Here’s a basic overview:
- Replace First Occurrence in a Line:
- To replace the first occurrence of a string in the current line, use the following command:
:s/old_string/new_string/Example:
:s/foo/bar/
- To replace the first occurrence of a string in the current line, use the following command:
- Replace All Occurrences in a Line:
- To replace all occurrences of a string in the current line, add the
gflag to the command::s/old_string/new_string/gExample:
:s/foo/bar/g
- To replace all occurrences of a string in the current line, add the
- Replace Only Whole Words:
- To replace only whole words (not substrings), use the
\bword boundary marker::s/\bold_string\b/new_string/gExample:
:s/\bfoo\b/bar/g
- To replace only whole words (not substrings), use the
- Replace in a Range of Lines:
- To replace in a range of lines, specify the range before the
scommand::1,10s/old_string/new_string/gThis example replaces in lines 1 to 10.
- To replace in a range of lines, specify the range before the
- Replace and Confirm Each Change:
- To confirm each change interactively, add the
cflag::%s/old_string/new_string/gcThis example replaces globally in the entire file (
%represents the whole file) and prompts for confirmation.
- To confirm each change interactively, add the
- Replace and Save Changes in a File:
- To replace and save changes in the file, use the
:wcommand after the substitution command::%s/old_string/new_string/g | w
- To replace and save changes in the file, use the