乐闻世界logo
搜索文章和话题

How to replace a character by a newline in Vim

1个答案

1

Replacing characters with newline in Vim can be achieved using Vim's substitution command. Here is a step-by-step guide along with a practical example.

Step-by-Step Guide:

  1. Open Vim: First, open Vim and load the file you wish to edit.

  2. Enter Command Mode: Ensure you are in command mode, not insert mode or visual mode.

  3. Use Substitution Commands: Use :s for local substitution or :%s for global substitution. The % symbol denotes operating on the entire file.

  4. Specify the Characters to Replace and the Newline: In Vim, the newline character is represented by (carriage return is represented by ). For example, to replace all commas , with newline characters, use the following command:

vim
:%s/,/\n/g

Here, , is the character to replace, \n is the newline character, and the g flag ensures global replacement, meaning all occurrences on each line are replaced.

Practical Example:

Suppose you have a text file containing:

shell
apple,banana,orange grape,mango,pineapple

Replace each comma with a newline so each word occupies its own line. Using the command above:

vim
:%s/,/\n/g

The file content after replacement will be:

shell
apple banana orange grape mango pineapple

This way, each word previously separated by commas now occupies its own line, which is useful for tasks like converting CSV format to column format.

Tips:

  • Ensure you have backed up the file before executing the substitution command to prevent unexpected results.
  • Use the g flag to replace all occurrences on each line; omit it if you only want to replace the first occurrence per line.
2024年7月20日 15:18 回复

你的答案