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

How do I swap the first two comma-separated fields on each line with one substitute command?

Answer

:%s/\v^([^,]+),([^,]+),/\2,\1,/<CR>

Explanation

When CSV-like data has two columns in the wrong order, manually fixing each line is slow and error-prone. A single substitution with capture groups can swap fields across the whole buffer instantly. This is a strong pattern for structured text refactors where delimiters are stable.

How it works

  • :%s/.../.../ runs substitution on every line in the file
  • \v enables very-magic regex mode for cleaner grouping syntax
  • ^([^,]+),([^,]+), captures the first field as \1 and second as \2
  • \2,\1, writes them back in reversed order while preserving the remainder of each line

Because the pattern anchors at line start and consumes only the first two comma-separated chunks, later columns are untouched.

Example

Before:

alpha,beta,gamma
one,two,three

Run:

:%s/\v^([^,]+),([^,]+),/\2,\1,/

After:

beta,alpha,gamma
two,one,three

Tips

  • Add g only if your pattern can match more than once per line
  • Use c (.../gc) when you want confirmation before each swap
  • If fields can contain commas inside quotes, switch to a CSV-aware tool instead of regex

Next

How do I open the alternate buffer in a new split while keeping my current window unchanged?