Vim Substitution


Substituting text within Vim is a powerful editing feature, allowing for complex replacements and manipulations. This goes beyond simple find-and-replace functionality, offering pattern matching and special characters for fine-grained control.

The basic substitution command in Vim follows this structure:

:s/{pattern}/{replacement}/{flags}

Let’s break down each component:

Examples:

   :s/apple/orange

Here, % represents all lines, and g stands for global.

   :%s/apple/orange/gc

The c flag prompts for confirmation.

   :%s/\d\+a/X/g

Here, \d\+ represents one or more digits.

   :s/\(\w\+\) \(\w\+\)/\2 \1/

The \(...\) define capture groups, and \1 and \2 refer to the captured text.


    :s/apple/apple (&)/

`&` represents the entire matched pattern.  You can also use `\0`.  Similarly, `\1`, `\2`, etc., refer to captured groups if regular expressions are used.

Beyond the Basics:

The substitution command offers much more. Experiment with different regular expressions and flags to harness its full potential. The :help :s command within Vim provides comprehensive documentation on all the options available. Mastering substitution will significantly enhance your text editing efficiency in Vim.