Vim: a replacement in a range that is less than a line

Let's say I have the following line of code:

something:somethingElse:anotherThing:woahYetAnotherThing 

And I want to replace each : with ; except the first, so the line looks like this:

 something:somethingElse;anotherThing;woahYetAnotherThing 

Is there a way to do this with the command :[range]s/[search]/[replace]/[options] without using the c parameter to confirm each replacement operation?

As far as I can tell, the smallest range s acts on is one line. If so, what is the fastest way to accomplish the above task?

+6
source share
4 answers

I am new to vim; I think you are right that the range is just lines (not 100%), but for this specific example, you can try replacing all instances with a global flag, and then return the first one by omitting the global one - something like :s/:/;/g|s/;/:/ .

Note: if the string contains ; to the first : then it won’t work.

+6
source

Here is how you could use a single keystroke to accomplish what you want (by matching capital Q):

map Q :s/:/;/g\|:s/;/:<Enter>j

Each time you press Q, the current line will be changed, and the cursor will move to the next line.

In other words, you can simply press Q several times to edit each subsequent line.

Explanation:

This will work globally on the current line:

:s/:/;/g

This will cause the first half-bell to return to the colon:

:s/;/:

@AlliedEnvy's answer combines them into one statement.

My map command assigns @AlliedEnvy a response to the Q character.


Another approach (which I would probably do if I only had to do it once):

f:; r ; ; .

Then you can click several times ; . until you reach the end of the line.

(Your choice to replace the half-hour is done by several of the community)

Explanation:

  • f : - go to the first colon
  • ; - go to the next colon (repeat the search in the line)
  • r ; - replace the current character with a semicolon
  • ; - repeat the last search in the line (again)
  • . - repeat the last command (replace the current character with a semicolon)

In short:

  • f x - moves to the next occurrence x in the current line
  • ; repeats the last built-in search
+2
source

Here you go ...

 :%s/\(:.*\):/\1;/|&|&|&|& 

This is a simple regex replacement that takes care of one non-first :

The & command repeats the last change.

Syntax | splits several commands on one line. Thus, each substitute is repeated as many times as there is |& .

+2
source

While the other answers work well for this particular case, here is a more general solution:

Create a visual selection from the second item to the end of the line. Then limit the replacement to the visual area by including \%V :

 :'<,'>s/\%V:/;/g 

Alternatively, you can use the vis.vim plugin

 :'<,'>B s/:/;/g 
+2
source

All Articles