问题
For example, I have a text , 10 3 4 2 10 , 4 ,10 ....
No I want to change each 10 with different words
I know %s/10/replace-words/gc but it only let me replace interactively like yes/no but I want to change each occurrence of 10 with different words like replace1, 3, 4 , 2 , replace2, 4, replace3 ....
回答1:
Replaces each occurence of 10
with replace{index_of_match}
:
:let @a=1 | %s/10/\='replace'.(@a+setreg('a',@a+1))/g
Replaces each occurence of 10
with a word from a predefined array:
:let b = ['foo', 'bar', 'vim'] | %s/10/\=(remove(b, 0))/g
Replaces each occurence of 10
with a word from a predefined array, and the index of the match:
:let @a=1 | let b = ['foo', 'bar', 'vim'] | %s/10/\=(b[@a-1]).(@a+setreg('a',@a+1))/g
But since you have to type in any word anyway, the benefit of the second and third function this is minimal. See the answer from SpoonMeiser for the "manual" solution.
Update: As wished, the explanation for the regex part in the second example:
%
= on every line in the documents/<search>/<replace>/g
= s
means do a search & replace, g
means replace every occurence.\=
interprets the following as code.remove(b, 0)
removes the element at index 0 of the list b
and returns it.
so for the first occurrence. the line will be %s/10/foo/g
the second time, the list is now only ['bar', 'vim']
so the line will be %s/10/bar/g
and so on
Note: This is a quick draft, and unlikely the best & cleanest way to achieve it, if somebody wants to improve it, feel free to add a comment
回答2:
Is there a pattern to the words you want or would you want to type each word at each occurrence of the word you're replacing?
If I were replacing each instance of "10" with a different word, I'd probably do it somewhat manually:
/10
cw
<type word>ESC
ncw
<type word>ESC
ncw
<type word>ESC
Which doesn't seem too onerous, if each word is different and has to be typed separately anyway.
来源:https://stackoverflow.com/questions/43539251/how-to-replace-finding-words-with-the-different-in-each-occurrence-in-vi-vim-edi