Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a register value as search pattern

Tags:

vim

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 register 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
like image 613
pkit Avatar asked Oct 13 '10 09:10

pkit


3 Answers

I don't think it's possible directly, but you can use :exe to achieve this:

:exe '%s/' . @a . '/foo/g'
like image 156
DrAl Avatar answered Jan 02 '23 19:01

DrAl


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
like image 35
Benoit Avatar answered Jan 02 '23 20:01

Benoit


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:

  1. Search for foo
  2. %s//\=@a/g (or highlight some text and start typing :s to substitute only in that range)
like image 35
Nathan Long Avatar answered Jan 02 '23 19:01

Nathan Long