Why doesn't \n insert a newline in a :s replacement, and what should I use instead?
Answer
:%s/,/,\r/g
Explanation
In Vim substitutions, \n and \r behave differently depending on whether they appear in the search pattern or the replacement string — a common gotcha that surprises even experienced users.
How it works
In the search pattern:
\n— matches a newline (end of line)\r— matches a carriage return (\r, ASCII 13)
In the replacement string:
\r— inserts a real newline (splits the line)\n— inserts a null byte (not a newline!)
So to split a line at a delimiter, use \r, not \n, in the replacement.
Example
Given a comma-separated line:
apple,banana,cherry
Running :%s/,/,\r/g splits it into multiple lines:
apple,
banana,
cherry
Using :%s/,/,\n/g instead inserts null bytes — the file appears unchanged or corrupted.
Conversely, to search for and remove newlines between lines, use \n in the search side:
:%s/\n/ /g
This joins all lines into one by replacing each newline with a space.
Tips
- Remember:
\rin replacement = newline,\nin search = newline — they're on opposite sides - To join lines without a separator:
:%s/\n//g - In very magic mode (
\v), the same rule applies:\rin replacement,\nin pattern