vimtricks.wiki Concise Vim tricks, one at a time.

How do I swap two parts of a line using capture groups in a Vim substitution?

Answer

:s/\v(pattern1)(pattern2)/\2\1/

Explanation

Vim's substitute command supports capture groups (also called backreferences), which let you rearrange matched portions of text. By wrapping parts of the pattern in parentheses and referencing them with \1, \2, etc. in the replacement, you can swap, reorder, or restructure text with a single command.

How it works

  • \v — enables "very magic" mode so parentheses () work as groups without escaping
  • (pattern1) — first capture group, referenced as \1 in the replacement
  • (pattern2) — second capture group, referenced as \2
  • \2\1 — the replacement reverses the order of the two captured groups

Without \v, you would need \( and \) to create groups, making the pattern harder to read.

Example

Given a CSV-like line:

John,Smith
Jane,Doe

Running :%s/\v(\w+),(\w+)/\2,\1/ produces:

Smith,John
Doe,Jane

The first and last names are swapped.

Tips

  • You can use more than two groups: \1, \2, \3, etc.
  • Add literal text in the replacement: \2 - \1 inserts - between swapped groups
  • Use \0 or & to reference the entire match
  • Combine with % to apply across the whole file: :%s/\v.../\2\1/g

Next

How do I ignore whitespace changes when using Vim's diff mode?