Here’s a question from Mr. Ashi, a regular reader at Techglimpse. He asks, how to insert text at the beginning of each line in Vim editor?
I just wanted to know if there’s a Vim command to insert a text at the start of each line? Say, I want to insert ‘hello’ at the beginning of each line?
How to insert text at the beginning of each line in Vim editor?
Yes, that’s possible. You can use substitute command as shown below:
# vim sample.txt
Method 1: Type the below command and hit enter.
Assume that you want to add a space or any other special character, then just append the same to the text.
:%s/^/hello : /
You can also insert text at the beginning from line 10 to 20 (i mean, the range).
:10,20s/^/hello : /
Note: The above example inserts text at the beginning of 10th line to 20th line. Lookout for the
missing %, which means substitute all lines.
Method 2: Using marker
Step 1: Move cursor to the line from where you want to insert text.
Step 2: Hit
ESC and type
ma. This step will create a marker
Step 3: Move cursor to the line till where you want to stop inserting the text.
Step 4: Type
:'a,.s/^/hello : /
Well, the command might look complex, but it’s something similar to using range. At Step 2, we create a new marker
a. Then, the command starts with
typewriter apostrophe ( ' ) followed by marker
a – denoting a start of the line at marker and comma
( , ) followed by
dot (.) and s command- denoting end of the substitute. Carrot
( ^ ) represents beginning of the line.
Method 3: Using Visual editor.
Step 1: Move the cursor to the line from where you would like to insert the text.
Step 2: Hit
Ctrl + V to enter into
Visual Block and use cursor to
select the first column till line where you want to stop inserting the text.
Step 3: Hit
Shift + i to enter into insert mode. Type text you would like to insert and hit
ESC. You will see the text being insert automatically to all the lines selected in Step 2.
That’s it! Love the trick? Let us know your comments.
Comments Leave a Comment