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 gg"ayG :bdelete :%s/MyOldString/\=@a/g
:edit MyOtherFile.txtThis command creates a new buffer and open the file MyOtherFileFile.txt.
ggGo to the top of the file.
"aUse named buffer a
yGYank (y) all text (G)
:bdeletedelete the file buffer (MyOtherFile.txt) and go back to the original file
:%s/MyOldString/\=@a/gsearch 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