CSV search and replace

纵饮孤独 提交于 2020-01-21 09:17:05

问题


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

回答1:


If 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 detailed description of the technique.)

In case of substitution values that differ essentially from each other, change the command to substitute not a serial number of an occurrence, but an item of a replacement list with that number as an index.

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

To perform the substitutions on every line independently of each other, use the :global command to iterate one of the above commands through the lines of a buffer.

: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:


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


来源:https://stackoverflow.com/questions/7366430/csv-search-and-replace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!