Use a register value as search pattern
I wish to use the content of a register as search pattern in Vim.
I would like to do this from the command line so I cannot use the <c-r>
syntax since that assumes an interactive session.
It is possible to use a regis开发者_Go百科ter as a replace pattern, like this
:%s/foo/\=@a/g
However using this syntax as a search pattern does not work
:%s/\=@a/foo/g
it outputs
E64: \= follows nothing
E476: Invalid command
In a pattern (not the replacement part), \=
stands for “0 or 1 time” (it is a synonym for \?
put should be preferred over \?
since the latter means a literal ?
when looking backwards.
See :help /\=
and help pattern
for more details.
Why not :
let @/=@a
%s//foo/g
I don't think it's possible directly, but you can use :exe
to achieve this:
:exe '%s/' . @a . '/foo/g'
You can do this with the /
register
This doesn't solve the general problem, but it appears to me that the /
register is special in this regard: if you leave the search term blank, it will use whatever is in the /
register; namely, whatever you searched for last.
So if you want to replace foo
with the contents of @a
, you could do this:
- Search for
foo
%s//\=@a/g
(or highlight some text and start typing:s
to substitute only in that range)
精彩评论