Finding the nth match in a string in vim

I am editing a wiki file and I want to add a new column between two columns.

| *No* | *Issue* | *File* | *Status* | | 1 | blah | foo | open | | 2 | blah1 | foo1 | close | 

now between the third and fourth columns I want to insert another column for which, if I could look for a fourth match for "|" character in the given line, I can replace it with "| |". How can this be done with vim?

The end result will be something like

 | *No* | *Issue* | *File* | | *Status* | | 1 | blah | foo | | open | | 2 | blah1 | foo1 | | close | 
+4
source share
4 answers

How to write a macro to the q register by typing qq3f|a|<ESC>q in command mode (ESC means pressing the Escape key). Now you can apply this macro to each line :% norm@q .

Extra bonus:

Using this template, you can add more complex actions, for example, replicate the first column as column 3 (if the cursor is in the first column):

 qqf yf|;;;p0q 

Oh, and the answer to your question: search for the 4th occurrence | the line runs 3f| (if the cursor is at position 0 and on the symbol | , as in your example).

+3
source

Consider the following substitution command.

 :%s/\%(.\{-}|\)\{4}\zs/ |/ 
+1
source

You can call sed in vim as a filter:

 :%!sed 's/|/| |/3' 
0
source
 :%s/\(|[^|]*\)\{3\}/&| / 

This means: on each line ( % ), find three occurrences ( \{3\} ) of the line that begins with | followed by any number of non | ( [^|]* ) and replace it with yourself ( & ) and then | .

0
source

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


All Articles