Find and Replace Multiple Files in Telescope
Here's how to find and replace a pattern over many files in nvim via telescope.
Install telescope
Via lazy.nvim:
{
"nvim-telescope/telescope.nvim",
dependencies = {
"nvim-lua/plenary.nvim",
"BurntSushi/ripgrep",
},
cmd = "Telescope",
lazy = true,
config = function()
require("telescope").setup()
end,
},
This defines the main package to install. It defines dependencies. The lazy
opt means that it won't be loaded at startup. The cmd
specifies when the plugin will load (ie, when the :Telescope
command is first run).
Live grep with Telescope
Now, find a string pattern in your files. Via lua:
require('telescope.builtin').live_grep()
This will bring up a finder. Type your pattern. You'll see rows for hits.
Save to the Quick Fix buffer
The quick fix buffer allows you to save your hit results. And later, we'll be able to modify the files in this buffer.
Telescope can save your hit results to the Quick Fix buffer by pressing C-Q
by default. I'm not sure what command that's running.
Modify each file
While in the Quick Fix buffer, run the command to search and replace, save each of the affected files and close thier buffers. Here's the one piped command to do those 3 steps:
:cfdo %s/mystring/newstring/g | update | bd
cfdo
runs this command over each file in the Quick Fix list. %s
is a buffer-wride search. /g
is a global (multiple per-line) search. The |
pipe sends the output of the first command to the input of the next. update
saves modified buffers. bd
closes the buffers.
You have now found string patterns, made edits, and saved multiple files.