vim search & replace string with a file content.


Today, a colleague of mine came with an interesting question: how can I search & replace a string with the content of a file. I naturally thought of vim.
I started digging, but couldn’t find a direct way to do it. So, I decided to use a named buffer to hold the content of the file.
So let’s say that you are editing a file A (current buffer) and want to replace all occurrences of MyOldString with the content of MyOtherFile.txt.
Here is the way to do it:
While editing your file, type the following commands:

:edit MyOtherFile.txt gg“ayG :bdelete :%s/MyOldString/\=@a/g

Some explanation:

  • :edit MyOtherFile.txt This command creates a new buffer and opens the file MyOtherFile.txt.
  • gg Go to the top of the file.
  • "a Use named buffer a
  • yG Yank (y) all text (G)
  • :bdelete Delete the file buffer (MyOtherFile.txt) and go back to the original file.
  • :%s/MyOldString/\=@a/g Search the whole file (:%s) for the string MyOldString and replace it with the content of named buffer (\=@a) for all occurrences (g).

This is quite useful in some cases. This could be transformed into a named macro…

Any other method to vim search & replace a string with a file content (or without vim) is welcome.

Comments