Search and replace CSV

I want to replace a series of pipeline characters with different values, how would I do this with regular expressions?

Example:

This | is | a | sentence And | this | is | the | second | one 

Final result:

 This new is new2 a new3 sentence And new this new2 is new3 the new4 second new5 one 
+2
source share
2 answers

If the substitution values ​​differ only in the numbers at the ends, use the command

 :let n=[0] | %s/|/\='new'.map(n,'v:val+1')[0]/g 

(See my answer to the question " gVim find / replace with counter " for a detailed description of the technique.)

In the case of substitution values ​​that differ significantly from each other, change the command to replace not the serial number of the occurrence, but the item a list of notes with this number as an index.

 :let n=[-1] | %s/|/\=['one','two','three'][map(n,'v:val+1')[0]]/g 

To perform replacements on each line independently, use the :global command to iterate one of the above commands along the buffer lines.

 :g/^/let n=[0] | s/|/\='new'.map(n,'v:val+1')[0]/g 

Similarly

 :g/^/let n=[-1] | s/|/\=['one','two','three'][map(n,'v:val+1')[0]]/g 
+2
source

Define a function:

 fun CountUp() let ret = g:i let g:i = g:i + 1 return ret endf 

Now use:

 :let i = 1 | %s/|/\="new" . CountUp()/g 
0
source

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


All Articles