Regular expression in Vim - insert blank line before numbered lines

I have the 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 an empty line before each numbered line so that the text above looks like this:

 Title line 1. First list First line Second line 2. Second list Oranges Mangoes 3. Stationary Pen Pencils Etc 

I tried the following code, but it does not work:

 %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. Thank you for your help.

+5
source share
3 answers

You should avoid parentheses in VIM syntax to keep in mind a special cluster:

 %s/^\(\d\)/\r\1/g 

Or use a token with a zero matching width ( \ze ):

 %s/^\ze\d/\r 
+4
source

To use capture group () without avoiding them, use \v very magic (see :h /magic )

 :%s/\v^(\d)/\r\1/ 

Note that the g flag is superfluous since there can only be one match at the beginning of a line

Since the replacement section requires an entire consistent line, you can simply use & or \0 without requiring an explicit capture group

 :%s/^\d/\r&/ 


Mentioned in comments

 :g/^\d/norm O 

The g command allows you to filter lines and execute a command on these lines, for example norm O , to open a new line above. The default range is the full file, so % not required

With the substitute command, this will be :g/^\d/s/^/\r/

See :h :g and :h ex-cmd-index for a complete list of commands for use with :g

+3
source

You can use the global command :g to execute an empty :put on each line before the corresponding number ^\d .

 :g/^\d/pu!_ 

Note. Using the black hole case, "_ , combined with :put , to give us an empty string.

For more help see:

 :h :g :h /\d :h :put :h quote_ 
+1
source

Source: https://habr.com/ru/post/1269485/


All Articles