Saturday, September 19, 2020

Re: How to replace string in specific paragraph only?

On 2020-09-19 14:06, 'Grant Taylor' via vim_use wrote:
> > :g/aaa/norm vip:s//bbb^V^M
> >
> > where ^V^M is a control-V followed by a control-M (which makes
> > this nasty to put in a mapping or vimrc). This works because vim
> > knows that a "paragraph" is bounded by empty lines *or* BOF/EOF
> > and does the ugly work for us.
>
> ACK
>
> Would it be worth while to include word boundaries \< and \> so
> that you don't accidentally get a sub-string?

My assumption was that "aaa" was a meta-regex that matched whatever
was needed, including any word-boundaries or other matching/context
the OP needed.

> Also, is there any way to group the first "aaa" so that it could be
> (back) referenced in the substitution? }:-)

Depends on what you mean. There are multiple regex in play:

- the thing looked for in the g/first/

- the boundary looked for when looking backwards (empty line or BOF)

- the boundary looked for when looking forwards (empty line or EOF)

- the thing looked for in the s// command

Using the :norm method, you don't have the two boundary regexen to
change the most-recently-used-search, so the regex in the :g can be
preserved into the :s// command so you don't have to duplicate it.

Either way, whatever regex the :s// searches for can capture all (for
replacement with "&") or subsets (with "\(…\)" for replacements with
"\1" through "\9"), and then use those captured bits in the
replacement. Including if you use the :norm method and capture them
in the :g portion. Here I look for "G" followed by any number of "C"s
followed by another "G" and then replace them with a "T" followed by
the "C"s we captured, followed by another "T":

:g/G\(C*\)G/norm vip:s//T\1T/g^V^M

-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.
To view this discussion on the web visit https://groups.google.com/d/msgid/vim_use/20200919161307.63b79768%40bigbox.attlocal.net.

No comments: