Overview
It's often necessary to conduct a project-wide search and replace of a string, variable, class name, etc. when working on a project. Here is a quick and customizable way to conduct a search and replace using vim and :args
and :argdo
functionality.
Snippet
Create a file in the root directory of your project called sr.txt with the following contents:
:args `grep -rl \"trans('site.name\" --exclude-dir={storage,.git,assets,node_modules,vendor,lang}`
:argdo %s/trans('site.name')/trans('site.newName')/gec | wn
:update
Save and exit the file, and then call it from the command line with vim via:
vim -s sr.txt
Explanation
This will take all of the results returned by the command executed on the first line (starting :args
) and process each with the command specified on the 2nd line (starting :argdo
). In this example the search/replace command will be run on each file returned by the grep executed on line 1. Using grep here is useful to narrow down the list of files being operated on to include only files that contain the text we'd like to replace with our search/replace command. Otherwise vim will have to enter every file in the project to check itself if there are any matches in that file.
Within each file you'll be prompted to decide whether to execute the replacement or skip it. This is a bit more cautious and by adjusting the gec | wn
arguments to the search/replace command you can have it execute the replacements without prompting (which can be much faster if you're sure no mistakes will be made).