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

How do I swap the first two whitespace-separated columns on every line?

Answer

:%s/\v(\S+)\s+(\S+)/\2 \1/<CR>

Explanation

When you need to flip two fields across a whole file, a single substitution is faster and safer than recording a macro. This pattern is useful for quick data cleanup tasks like changing name id into id name before sorting or diffing. The \v flag keeps the regex readable so you can focus on the structure of the line instead of heavy escaping.

How it works

  • :%s runs a substitution on every line in the buffer
  • \v enables very magic mode, so grouping with () is concise
  • (\S+) captures the first non-space column
  • \s+ matches the separator whitespace between columns
  • (\S+) captures the second column
  • \2 \1 replaces with the second capture, then the first
  • <CR> executes the Ex command

Example

Before:

alice 100
bob   250
carol 400

After running the command:

100 alice
250 bob
400 carol

Tips

  • Add a global flag (g) if you intentionally want to swap repeated column pairs within the same line.
  • If your columns are comma-separated instead of space-separated, replace \s+ with , and keep the same capture/reorder strategy.

Next

How do I remove trailing spaces only within the currently selected visual block?