How to replace a character by a newline in Vim ?

To replace a character with a newline in Vim, use the substitution command (:s) with \r in the replacement string. Here’s how:

Basic Syntax

:%s/<CHARACTER>/\r/g
  • %: Apply to the entire file (remove for current line only).
  • <CHARACTER>: The character you want to replace (e.g., ,, ;, etc.).
  • \r: Represents a newline in the replacement string.
  • g: Replace all occurrences (not just the first one in each line).

Examples

1. Replace commas (,) with newlines:

:%s/,/\r/g

Before: Hello,World
After:

Hello
World

2. Replace semicolons (;) with newlines:

:%s/;/\r/g

3. Replace spaces with newlines:

:%s/ /\r/g

Edge Cases

Replace a literal backslash (\):

:%s/\\/\r/g
  • Use \\ to match a single backslash.

Replace a special regex character (e.g., . or *):

:%s/\./\r/g  # Replace literal `.` with newline
:%s/\*/\\r/g  # Replace `*` with newline

Notes

  • Visual Selection: Replace in a selected block:
  1. Highlight text in visual mode (V).
  2. Run :'<,'>s/,/\r/g.
  • Confirmation: Add /c to confirm each replacement:
  :%s/,/\r/gc
  • Line Endings: \r works for Unix (\n), Windows (\r\n), and Mac (\r) line endings.

Common Mistakes

  • Using \n instead of \r:
  • \n inserts a null byte (^@), not a newline.
  • Fix: Always use \r for newlines in replacements.

Summary

  • Use \r in the replacement string to insert a newline.
  • Escape special regex characters (e.g., ., *, \) with \.
  • Use %s for global replacements or limit to visual selections.

Leave a Reply

Your email address will not be published. Required fields are marked *