Is it possible to use vim find and replace to replace a variable with the current filename? for example, fancyFileName.txt contains

this is the VARIABLE to replace in this fancyFileName.txt

and I am trying to use something like :%s/VARIABLE/expand(%)/ to get

this is the fancyFileName.txt to replace in this fancyFileName.txt

2 Answers 2


As pointed out in other answers, :help sub-replace-special, and :help \=, you can use any expression as the replacement text like so:


In your case:

  • 1
    I check this as the answer because it is easier to write (at least for me). However I spent some time with help \=, which didn't help, until I realized the explanation is in the answer by Christian. It might be word pointing to it more clearly in the answer? Thanks!
    – manolius
    Apr 21, 2022 at 8:25
  • @manolius great feedback, thanks. Is the new version better?
    – D. Ben Knoble
    Apr 21, 2022 at 13:39
  • Yes! much appreciated for all the effort!
    – manolius
    Apr 21, 2022 at 15:10

Assuming you have defined VARIABLE as a global Vim Script variable like this:

:let g:VARIABLE='fanceFileName.txt'

you can then use:

%s/\<VARIABLE\>/\=get(g:, submatch(0), '')/g

This uses the special atom \= to evaluate the following as a VimScript expression using get(g:, 'VARIABLE', '') to access the variable from the global dictionary :g

See also :h sub-replace-special

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.