vim let search and replace with increment

淺唱寂寞╮ 提交于 2020-12-09 06:38:59

问题


i wanted to search and replace, implement after the thread here, unfortunately it does not work. gVim find/replace with counter

Can anyone help me?

Working

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

Not working

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

Why? how do I mask the functionon?

Example

{| class="wikitable"
! Number
! Name
! Type
! Default Value
! Duration
! Activation
! Status
! EDIT
|-
| 
| Adobe-Dummy-Cart-Total
| Custom Script
| 
| Pageview
| Active
| Approved
| Edit
|-
| 
| basePrice

I wana replace

|-
|

with

|-
| 1

|-
| 2

回答1:


When you use :help sub-replace-expression, the entire replacement must be a Vimscript expression (that starts with \=). You cannot just prepend replacement text (as in BLABLA\=map(n,'v:val+1'). Use string concatentation instead. A complication with your map approach is that this returns a List, not a String, so we need to select the only (counter) element of the List. To refer to the existing matched text, use submatch(0) instead of \0 or & (or avoid the need for a reference by using \zs at the end of the pattern instead).

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



回答2:


:help sub-replace-expression (emphasis mine)

When the substitute string starts with "\=" the remainder is interpreted as an expression.

You cannot do what you want; the replacement string is either a subexpression (when it starts with \=), or a literal (when it does not).

Instead, you need to rewrite the subexpression to concatenate the string programmatically (:help expr-.):

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

[0] to take the content of the array produced by map is necessary for two reasons: replacing with an array will introduce an unwanted newline, and make concatenation with a string impossible.

For your example though, it may not necessary, if you are not introducing any string besides the number - i.e. if you don't need that space (:help /\zs):

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

Of course, you can combine the two, for a perfect demoisturised solution to your specific situation:

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



回答3:


Using \zs we can make the solution easier

:let c=1 | g/^|-\n|\zs/ s//\=' '.c/g | let c+=1

^ ............ start of line
\n ........... line break
|  ........... vertical bar

We are concatenating a space \=' ' with the counter c



来源:https://stackoverflow.com/questions/54398235/vim-let-search-and-replace-with-increment

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