Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in Vim- inserting blank line before numbered lines

Tags:

regex

vim

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.

like image 210
rnso Avatar asked Jul 04 '17 15:07

rnso


People also ask

How do I insert a blank line in Vim?

Press Enter to insert a blank line below current, Shift + Enter to insert it above.

How do I add a line after a line in Vim?

Now if you want to add line break after a specific pattern, you can easily add line break '\r' after the cur pattern above. For example, if you want to add line break after '}' character in file data. css, you need to go to open the file in vi editor. Go to command mode, by hitting Esc key.


Video Answer


3 Answers

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
like image 134
revo Avatar answered Oct 03 '22 04:10

revo


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

like image 24
Sundeep Avatar answered Oct 03 '22 04:10

Sundeep


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_
like image 32
Peter Rincker Avatar answered Oct 03 '22 03:10

Peter Rincker