Wednesday, July 20, 2011

Re: substitute with list content

On 20/07/11 10:21, Chen San wrote:
> i have saw some usages in such a form:
>
> let i=1 | g/foo/s//\="blah_".i/ | let i=i+1
>
> then my question is, what if i wanna substitute something with a list,
> such as ['one','two','three']
>
> i have try the next script:
>
> let i=0
>
> let alist=['one','two','three']
>
> for n in alist
> g/foo/s//\=n/
> endfor
>
> let i=i+1
>
>
> but all the 'foo' there would be replaced with 'one', not the 'two' or
> 'three'.
>
> anyone have any ideas?
>
> thanks.

the problem with

for n in alist
g/foo/s//\=n/
endfor

is that you'll set n to 1, scan the whole file replacing foo by the
value of n (which is 1) then scan the whole file again with n=2, not
find any foo, etc.

Your first idea is in a better direction: I think that

:let i=1 | g/foo/s//\=i/g|let i+=1
or
:let i=1 | exe 'g/foo/s//\=i/g|let i+=1' | unlet i

would work, provided that there are no more occurrences of foo than the
length of the list. (the :let i+=1 is regarded here as part of the
argument of the :g command, so it is executed immediately after the
substitute on every matching line.)

The /g switch assumes that you want to replace every occurrence of
"foo", even several per line and even in the middle of a word. You can
of course restrict that by means of the following zero-length pattern items:

\< start of word
\> end of word
^ start of line
$ end of line

Best regards,
Tony.
--
Said a horny young girl from Milpitas,
"My favorite sport is coitus."
But a fullback from State
Made her period late,
And now she has athlete's fetus

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