Star Hackademy

Hacking and configuring, IT's a long and secret story…

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 tought to 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 file.
So let’s say that you are editing a file A (current buffer) and want to replace all occurences 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

Some explanation:

  • :edit MyOtherFile.txt This command creates a new buffer and open the file MyOtherFileFile.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 occurences (g).

This is quite usefull in some case. This could be transformed in a named macro…

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

Categorised as: DevOps

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.