How to add a word at the beginning of several lines in vim?

In Vim,

How to add a word at the beginning of all lines? Also how can I add it at the end?

Eg .. If I have

A
B
C
D

I want to do it

int A =
int B = 

etc..

+5
source share
5 answers

use the visual block mode ( Ctrl- v) to select the desired column, and then press I, enter the desired characters and pressEsc

So, in this case, you place the cursor on A, press Ctrl- v, go to D, press Iand enter int(it will appear only in the first line while you type it), and then press Esc, at that moment it will apply this insert to all visually selected parts.

, .

:he v_b_I Visual Block

+11

:

:%s/^/at the beginning/
:%s/$/at the end/
+7

:%s/.\+/int & =

+

+4

The global substitute should do i:

:%s/.\+/int & =/

Here's how it works: in the second part of the lookup (i.e. c int & =), the ampersand is replaced with what was processed in the first part ( .*). Since it .*matches the entire line, each line is selected as desired.

If you have empty lines (in which you do not want to replace), you can go with

:%s/^\S\+$/int & =/
+2
source

If you need to copy only the first word, follow these steps:

:%s/^\w\+/int & =/g

If you want to keep the indentation, follow these steps:

:%s/^\(\s*\)\(\w\+\)/\1int \2 =/g
+2
source

All Articles