简体   繁体   中英

Regex in Vim- inserting blank line before numbered lines

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.

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

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

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_

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM