# Why does the replacement of newlines making use of g/re/p just relate to every various other line in Vim?

Take into consideration:

foo
bar
....
bar
baz

.

After that:

:g/bar/s/\n/\r\r/g

.

all of a sudden returns:

foo
bar

bar
bar

bar
bar

...
baz

.

when I desire newlines after every bar. Yet:

:g/bar/p

.

returns:

bar
bar
...
bar

.

as anticipated and also if there are newlines in between all the bars I get what I anticipate-- an added newline after every line having bar. I addressed the trouble by using:

:%s/$bar.*$\n/\1\r\r/g

.

yet I 'd actually such as to have a far better understanding on what's taking place.

0
2019-05-07 01:50:19
Source Share

To recognize what's taking place at this degree of information, I assume you need to grab the resource code. So, pointing out vim-7.1.314/src/ex_cmds.c (comment ahead of the definition of ex_global()) :

This is applied in 2 passes : first we check the apply for the pattern and also set a mark for each and every line that (not) suits. second of all we execute the command for each and every line that has a mark. This is called for due to the fact that after removing lines we do not recognize where to look for the next suit.

Hence, if you delete a line in the :g' ed command, the mark for this line vanishes also. If you create a line in the :g' ed command, it will not be noted, so the command will not execute on it. In your instance, line 3 is accompanied line 2, so the mark on line 3 goes away, and also the next mark after line 2 is the one initially placed on line 4.

Additionally, ex_global establishes the global_busy variable, which creates a couple of commands, consisting of :s, to act a little in different ways. I do not assume the distinction matters below though.

0
2019-05-08 21:53:37
Source

Gilles has addressed your "why?", yet I assumed you could be curious about a less complex means to do what you desired.

I desire newlines after every bar.

As opposed to changing the line ending personality (hence signing up with the lines and also shedding the inner mark, per Gilles' solution), add an empty line right prior to completion of each matching line. Usage $ to get an absolutely no - size suit right prior to completion of the line and also insert a line break there (additionally no demand for the /g modifier given that the pattern will just match as soon as per line). :g/bar/s/$/\r/

0
2019-05-08 07:53:09
Source