[vim] How to add text at the end of each line in Vim?

In Vim, I have the following text:

key => value1
key => value2
key => value1111
key => value12
key => value1122222

I would like to add "," at the end of each line. The previous text will become the following:

key => value1,
key => value2,
key => value1111,
key => value12,
key => value1122222,

Does anyone know how to do this? Is it possible to use visual block mode to accomplish this?

This question is related to vim

The answer is


If you want to add ',' at end of the lines starting with 'key', use:

:%s/key.*$/&,

Following Macro can also be used to accomplish your task.

qqA,^[0jq4@q

:%s/$/,/g

$ matches end of line


Another solution, using another great feature:

:'<,'>norm A,

See :help :normal.


I have <M-DOWN>(alt down arrow) mapped to <DOWN>. so that I can repeat the last command on a series of lines very quickly. with this mapping I can:

A,<ESC>

And then hold alt while pressing down repeatedly to append the comma to the end of each line.
This works well for me because it allows very good control over what lines do and do not get the change.
(I also have the other arrows mapped similarly to allow for easy repeating of .)

Here's the mapping line to paste into your vimrc:

map <M-DOWN> <DOWN>.

The substitute command can be applied to a visual selection. Make a visual block over the lines that you want to change, and type :, and notice that the command-line is initialized like this: :'<,'>. This means that the substitute command will operate on the visual selection, like so:

:'<,'>s/$/,/

And this is a substitution that should work for your example, assuming that you really want the comma at the end of each line as you've mentioned. If there are trailing spaces, then you may need to adjust the command accordingly:

:'<,'>s/\s*$/,/

This will replace any amount of whitespace preceding the end of the line with a comma, effectively removing trailing whitespace.

The same commands can operate on a range of lines, e.g. for the next 5 lines: :,+5s/$/,/, or for the entire buffer: :%s/$/,/.


ex mode is easiest:

:%s/$/,

: - enter command mode
% - for every line
s/ - substitute
$ - the end of the line
/ - and change it to
, - a comma

There is in fact a way to do this using Visual block mode. Simply pressing $A in Visual block mode appends to the end of all lines in the selection. The appended text will appear on all lines as soon as you press Esc.

So this is a possible solution:

vip<C-V>$A,<Esc>

That is, in Normal mode, Visual select a paragraph vip, switch to Visual block mode CTRLV, append to all lines $A a comma ,, then press Esc to confirm.

The documentation is at :h v_b_A. There is even an illustration of how it works in the examples section: :h v_b_A_example.