Saturday, May 22, 2010

Re: Replacements with return

On 2010-05-22, leandromartinez98 wrote:
> I'm trying do replace strings that contain return characters. For
> example,
> I would like to change:
>
> ----
>
> 0
> 0
> ----
>
>
> to
>
> ----
>
> 1
> 1
>
> ---
>
> I tried many things, as:
>
> :g/\n0\n/s//\n1\n/g
> :g/\n0\n/s//\r1\r/g
> (and all combinations of \r and \n possible)
> and variations of that using ^V+Return, ^V+^M.
>
> None of the combinations above give the correct result. For
> instance, :g/\n0\n/s//\n1\n/g results in:
>
> -----
> ^@1^@0
> -----
>
> And :g/\n0\n/s//\r1\r/g
>
> results in:
>
> ----
>
> 1
> 0
>
> ----
>
> I'm not getting the logic. Is there any symbol which represents
> the return character uniquely and acts in search/replace as a
> normal character?

If all you're searching for are strings that are bounded by
newlines, and not strings that contain newlines, I think you would
get better results using ^ to anchor the string to the beginning of
a line and $ to anchor it to the end of a line, like this:

:%s/^0$/1/

Note that ^ and $ match the beginning and end of the line with zero
width--they don't match a newline character--so no newlines need to
be included in the replacement string.

The reason your last example didn't work as you expected was that
your buffer contained

\n0\n0\n

and your pattern was

\n0\n

Your pattern matched the first three characters. After the
replacement was made, the search resumed with the next character in
the buffer, which was the second 0. The pattern did not consider
the newline preceding the second 0 because that newline had already
been consumed by the first match. That's one reason ^ and $ can be
more useful than \n for anchoring patterns to the ends of lines.

HTH,
Gary

--
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

No comments:

Post a Comment