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:
- First, open Vim: Launch your terminal, start Vim, and open the relevant file. For example:
bashvim example.txt
-
Enter Visual Line Mode: Navigate to the first line where you want to start inserting text. Press
Shift + Vto enter Visual Line Mode, which highlights the current line. -
Select multiple lines: Use the
jkey to move down or thekkey to move up, selecting consecutive lines where you want to insert text at the beginning. -
Insert text: After selecting the lines, press
:to display the range:'<,'>at the bottom, indicating the selected lines. Then typenorm I(note thatIis 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.
- Complete editing: Press
Escto 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.