How do I swap two adjacent words on a line using a substitute command in Vim?
Answer
:s/\v(\w+)\s+(\w+)/\2 \1/
Explanation
By using capture groups in a substitute command with very magic mode (\v), you can swap two adjacent words in a single operation. This technique is useful for quickly reversing argument order, fixing word transpositions, or restructuring identifiers.
How it works
:s/— Starts a substitute on the current line.\v— Enables very magic mode: parentheses and+have special meaning without backslashes, making the pattern more readable.(\w+)— Captures the first word (letters, digits, and underscores).\s+— Matches one or more whitespace characters separating the two words.(\w+)— Captures the second word./\2 \1/— Replacement: second captured group, a space, first captured group.
Example
Before: foo bar
After: bar foo
Swap function arguments (keeping the separator):
:s/\v(\w+),\s*(\w+)/\2, \1/
Before: move(width, height)
After: move(height, width)
Tips
- Add the
gflag to swap every adjacent word pair on the line::s/\v(\w+)\s+(\w+)/\2 \1/g - Use
:%s/...to apply to the whole file. - Without
\v, escape the parentheses::s/\(\w\+\)\s\+\(\w\+\)/\2 \1/ - To swap only within a visual selection:
:'<,'>s/\v(\w+)\s+(\w+)/\2 \1/