Search code examples
vimvi

Search for pattern and add sequential number to end of each line where pattern occurs


I want to search for a pattern and add sequential number to end of line. For example, I have following text file.

Male
John  #
Tom   #
Jack  #

Female
Mary  #
Jenny #

I want to search pattern "#" and add sequential number end of line.

Male
John  #0
Tom   #1
Jack  #2

Female
Mary  #3
Jenny #4

Solution

  • You could substitute with ascending numbers, as explained in this tip from the Vim Wiki:

    :let i=1 | g/#$/s//\='#'.i/ | let i=i+1