Search code examples
linuxvimvi

Vim :s replace specific N < g occurrences on a line


i am try to use a comma (,) to separate the thousands in the first two numeric fields using vim command

%s/\([0-9]\)\([0-9]\)\([0-9]\)\([0-9]\);/\1,\2\3\4;/g

but in this case it gonna add comma also to 9,995 in the second line , what can i use to replace specific N < g occurrences .

input

BitstreamCyberCJK;Freeware;30275;28686;v2.0 ;beta (1998-03-17)
Y.OzFontN;Freeware;21957;7621;v13.00 sfnt rev 9995; Pen-Ji (2010-08-24)

expected output

 BitstreamCyberCJK;Freeware;30,275;28,686;v2.0 ;beta (1998-03-17)
 Y.OzFontN;Freeware;21,957;7,621;v13.00 sfnt rev 9995; Pen-Ji (2010-08-24)

Solution

  • There is a way to repeat the last command: @: also, you could specify the number of repeats, for example: 10@:.

    So, start from replacing only first match: %s/\([0-9]\)\([0-9]\)\([0-9]\)\([0-9]\);/\1,\2\3\4;/

    Then, as we already have done one of N substitution, repeat it N-1 times.

    For example, to replace the first 10 numbers, use:

    %s/\([0-9]\)\([0-9]\)\([0-9]\)\([0-9]\);/\1,\2\3\4;/
    9@: