How can I add a string to the end of each line in Vim?

I want to add * to the end of each line in Vim.

I tried the code unsuccessfully

:%s/\n/*\n/g

Upvotes: 345

Views: 402879

Answers (10)

dirkgently
dirkgently

Reputation: 111120

:%s/$/\*/g

should work and so should :%s/$/*/g.

Upvotes: 432

nicole
nicole

Reputation: 831

I think using visual block mode is a better and more versatile method for dealing with this type of thing. Here's an example:

This is the First line.  
This is the second.  
The third.

To insert " Hello world." (space + clipboard) at the end of each of these lines:

  • On a character in the first line, press Ctrl-V (or Ctrl-Q if Ctrl-V is paste).
  • Press jj to extend the visual block over three lines.
  • Press $ to extend the visual block to the end of each line. Press A then space then type Hello world. + then Esc.

The result is:

This is the First line. Hello world.  
This is the second. Hello world.  
The third. Hello world.  

(example from Vim.Wikia.com)

Upvotes: 83

paxdiablo
paxdiablo

Reputation: 881123

One option is:

:g/$/s//*

This will find every line end anchor and substitute it with *. I say "substitute" but, in actual fact, it's more of an append since the anchor is a special thing rather than a regular character. For more information, see Power of g - Examples.

Upvotes: 10

utkarsh
utkarsh

Reputation: 221

If u want to add Hello world at the end of each line:

:%s/$/HelloWorld/

If you want to do this for specific number of line say, from 20 to 30 use:

:20,30s/$/HelloWorld/

If u want to do this at start of each line then use:

:20,30s/^/HelloWorld/

Upvotes: 21

Pedro Norwego
Pedro Norwego

Reputation: 131

You don't really need the g at the end. So it becomes:

:%s/$/*

Or if you just want the * at the end of, say lines 14-18:

:14,18s/$/*

or

:14,18norm A*

Upvotes: 9

ng.
ng.

Reputation: 7189

%s/\s*$/\*/g

this will do the trick, and ensure leading spaces are ignored.

Upvotes: 3

User 1058612
User 1058612

Reputation: 3819

...and to prepend (add the beginning of) each line with *,

%s/^/*/g

Upvotes: 6

Cyber Oliveira
Cyber Oliveira

Reputation: 8596

Even shorter than the :search command:

:%norm A*

This is what it means:

 %       = for every line
 norm    = type the following commands
 A*      = append '*' to the end of current line

Upvotes: 508

Brian Carper
Brian Carper

Reputation: 72926

Also:

:g/$/norm A*

Also:

gg<Ctrl-v>G$A*<Esc>

Upvotes: 47

user42092
user42092

Reputation:

:%s/\n/*\r/g

Your first one is correct anywhere else, but Vim has to have different newline handling for some reason.

Upvotes: 4

Related Questions