Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

vim

vi

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)
like image 235
DOS HASAN Avatar asked Nov 01 '21 21:11

DOS HASAN


People also ask

How do you replace special characters in vi?

You can use all the special matching characters for searches in search-and-replace. Then press the Return key. Then and press Return. You can modify this command to halt the search and make vi query whether you want to make the replacement in each instance.

How do I change occurrences in Vim?

Change and repeat Search for text using / or for a word using * . In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish. From normal mode, search for the next occurrence that you want to replace ( n ) and press . to repeat the last change.

How do I find and replace every incident of a text string in Vim?

When you want to search for a string of text and replace it with another string of text, you can use the syntax :[range]s/search/replace/. The range is optional; if you just run :s/search/replace/, it will search only the current line and match only the first occurrence of a term.


2 Answers

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@:
like image 196
Alex Kosh Avatar answered Sep 29 '22 08:09

Alex Kosh


I would use a shorter and more manageable search pattern:

:%s/\(\d\)\(\d\{3}\);/\1,\2;/g

Then, I would drop the /g flag to only substitute the first match on each line, since the goal is specifically not to substitute all matches on all lines:

:%s/\(\d\)\(\d\{3}\);/\1,\2;

Then, I would repeat the last substitution on every line:

g&

See :help \d, :help \{, :help :s_flags, and :help g&.

like image 22
romainl Avatar answered Sep 29 '22 08:09

romainl