excray
excray

Reputation: 2858

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

In Vim,

How do i add a word at the beginning of all lines? Also how do i add it at end?

Eg.. If i have

A
B
C
D

I want to make it to

int A =
int B = 

etc..

Upvotes: 5

Views: 1210

Answers (5)

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56390

use visual block mode (Ctrl-v) to select the column you want, and then hit I, type the characters you want, and then hit Esc

So in this case, you'd put your cursor on A, hit Ctrl-v, go down to D, hit I and type int (it'll only appear on the first line while you type it), and then hit Esc at which point it'll apply that insert to all visually selected portions.

This works for anywhere in the document, beginning of line or end of line.

:he v_b_I for more info on Visual Block Insert

Upvotes: 11

René Nyffenegger
René Nyffenegger

Reputation: 40489

A global substitute should do i:

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

This is how it works: in the second part of the substitution (ie in the int & =) the ampersand is replaced with what machted in the first part (the .*). Since .* matches the entire line, each line is subsituted as wanted.

If you have empty lines (in which you don't want to have any replacements), you could go with a

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

Upvotes: 2

ArtBIT
ArtBIT

Reputation: 3989

If you need to copy just the first word, then do:

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

If you want to preserve indentation, then do:

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

Upvotes: 2

Sam
Sam

Reputation: 15310

:%s/.\+/int & =

+ won't match on empty lines

Upvotes: 4

Benoit
Benoit

Reputation: 79165

You can do this:

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

Upvotes: 7

Related Questions