Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace finding words with the different in each occurrence in VI/VIM editor ?

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

like image 280
Ramchandra Shahi Thakuri Avatar asked Dec 06 '25 15:12

Ramchandra Shahi Thakuri


2 Answers

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 document
s/<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

like image 117
Doktor OSwaldo Avatar answered Dec 09 '25 05:12

Doktor OSwaldo


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.

like image 21
SpoonMeiser Avatar answered Dec 09 '25 04:12

SpoonMeiser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!