Thursday, February 15, 2018

Re: Change only second match on a line...

On 2018-02-15 17:16, 'Grant Taylor' via vim_use wrote:
> Is there a way to change only the second (or any specific) instance
> of a pattern on a line?
>
> Sort of like how 's/old/new/' changes the first instance of "old"
> to "new", but for the second (or any specific) instance.

The easiest way on most platforms is to just pipe it through sed
which does the dirty work for you:

:%! sed 's/old/new/2'

If you don't have sed available...

> Extrapolating the above sequence out to subsequent instances would
> be more and more annoying.

...this would be the route you'd go.

:%s/old.\{-}\zsold/new

for just two, or more generically for an arbitrary Nth place (e.g.
N=4)

%s/\%(old\%(\%(old\)\@!.\)*\)\{3}\zsold/new

where the "3" is N-1. Indeed ugly. Thus my recommendation for the
simplicity of sed over the pure-vim solution. :-)

-tim




--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments: