Thursday, May 14, 2020

Re: How to search a match on a line and then make a change on the next line?

On 2020-05-14 12:27, boB Stepp wrote:
> On Thu, May 14, 2020 at 08:00:38AM -0500, Tim Chase wrote:
> > :%s/\(\<field \+\w*\)address2.*\n\s*\zs\zepobox\>/\1
>
> Thank you, this works. I had to look up some of the flags you used
> before I understood what you are doing. In my particular example I
> found I did not need to use "\+", "\<" and "\>" to get the desired
> result. But I suspect that you are using these to protect against
> scenarios I am not considering. Would you mind elaborating on why
> you included those additional flags?

The space followed by \+ requires at least one but possibly more than
one space between "field" and the start of the field-name. So it
takes into consideration

field work_address2 STANDARD FIELD -- note multiple spaces

The \< prevents strange situations like

greenfield work_address

by ensuring that "field" stands alone without junk at the beginning.
Unlikely, but handy to specify up front. Likewise the \> prevents
it from finding something like "pobox2". Which you might or might
not want. Adjust according to your requirements.

> As I am trying to understand the "why"s of all of this, it would be
> helpful for my understanding if someone would explain why my regex
> did not work as expected. I am still not seeing it.
> :g/\(field [[:alnum:]_]*\)address2/+s/pobox/\1pobox/

As best I understand, the items captured in the g// portion don't
carry over for reuse in the s// replacement (the s// resets the
capture groups). Otherwsie, I believe it would work since

:g/\(field [[:alnum:]_]*\)address2/+

correctly finds the first lines and

s/pobox/XYZ/

correctly does a substitution, merely lacking access to the captured
\1 group. If you add some brackets around the \1 you'll see the
effect:

:g/\(field [[:alnum:]_]*\)address2/+s/pobox/[\1]pobox/

you'll see resulting lines like

[]pobox

to show that the contents of \1 are empty.

Hope that helps,

-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/20200514125229.55461682%40bigbox.attlocal.net.

No comments: