Reputation: 24535
I have following text:
Title line
1. First list
First line
Second line
2. Second list
Oranges
Mangoes
3. Stationary
Pen
Pencils
Etc
I want to add a blank line before every numbered line, so that above text looks like following:
Title line
1. First list
First line
Second line
2. Second list
Oranges
Mangoes
3. Stationary
Pen
Pencils
Etc
I tried following code but it is not working:
%s/^(\d)/\r\1/g
and
%s/(^\d)/\r\1/g
and
%s/^([0-9])/\r\1/gc
Where is the problem and how can this be solved. Thanks for your help.
Upvotes: 5
Views: 166
Reputation: 45087
You can use the global command, :g
to execute an empty :put
on each line before the matching number, ^\d
.
:g/^\d/pu!_
Note: Using the blackhole register, "_
, combined with :put
to give us the empty line.
For more help see:
:h :g
:h /\d
:h :put
:h quote_
Upvotes: 1
Reputation: 23667
To use capture group ()
without having to escape them, use \v
very magic (See :h /magic
)
:%s/\v^(\d)/\r\1/
Note that g
flag is redundant as there can be only one match at beginning of line
As entire matched string is needed in replacement section, one can simply use &
or \0
without needing explicit capture group
:%s/^\d/\r&/
Mentioned in comments
:g/^\d/norm O
The g
command allows filtering lines and executing command on those lines, like norm O
to open new line above. Default range is entire file, so %
is not needed
With substitute command, this would be :g/^\d/s/^/\r/
See :h :g
and :h ex-cmd-index
for complete list of commands to use with :g
Upvotes: 3
Reputation: 48711
You should escape parentheses within a VIM syntax in order to mean it a special cluster:
%s/^\(\d\)/\r\1/g
Or use an end of match zero-width assertion (\ze
) token:
%s/^\ze\d/\r
Upvotes: 4