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

How to insert text at beginning of a multi-line selection in vi/Vim

1个答案

1

In vi or Vim, inserting text at the beginning of multiple lines is a common task, especially when working with large code or configuration files. To accomplish this, utilize Vim's visual mode along with specific commands. Here is a step-by-step example:

  1. First, open Vim: Launch your terminal, start Vim, and open the relevant file. For example:
bash
vim example.txt
  1. Enter Visual Line Mode: Navigate to the first line where you want to start inserting text. Press Shift + V to enter Visual Line Mode, which highlights the current line.

  2. Select multiple lines: Use the j key to move down or the k key to move up, selecting consecutive lines where you want to insert text at the beginning.

  3. Insert text: After selecting the lines, press : to display the range :'<,'> at the bottom, indicating the selected lines. Then type norm I (note that I is uppercase), followed by the text you want to insert at the beginning of each line. For example, if you want to insert # as a comment at the start of each line, you would input:

vim
:'<,'>norm I#

and press Enter.

  1. Complete editing: Press Esc to exit insert mode, then verify that the specified text has been inserted at the beginning of all selected lines.

This process leverages Vim's range selection and the norm command, which executes a series of normal mode commands on each line. Here, the I command is used to insert text at the beginning of each line.

2024年7月20日 15:21 回复

你的答案