Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for the Nth match in a line in Vim?

I am editing a wiki file and would like to add a new column in between of two existing columns.

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

Say, I want to insert a new column between the 3rd and 4th columns above. If I could search for the fourth match of the | character in a given line, I could replace that with | |. But how one can do that in Vim?

The end result would look like so:

| *No* | *Issue* | *File* | | *Status* | 
| 1 | blah | foo | | open |
| 2 | blah1 | foo1 | | close |
like image 646
ggaur Avatar asked Mar 15 '12 11:03

ggaur


2 Answers

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

Additional bonus:

With this pattern you can add more complex actions, for example replicate the first column as column 3 (if cursor is at first column):

qqf yf|;;;p0q

Oh, and the answer to your question: Search 4th occurrence of | on a line is done by 3f| (if the cursor is at position 0 and on a | character as in your example).

like image 120
hochl Avatar answered Nov 03 '22 20:11

hochl


Consider the following substitution command.

:%s/\%(.\{-}|\)\{4}\zs/ |/
like image 2
ib. Avatar answered Nov 03 '22 22:11

ib.