How to search & replace all occurences in vim?
knowledge vimI always struggle to remember things that I don’t use often. Here is my
attempt to keep my knowledge somewhere else than in my head.
One of them is specific to vim.
How to search a specific string pattern inside a project and replace all its occurences easily.
Let’s start with the initial statement, I want to replace all the linux
occurences by OpenBSD.
Find files that validate the pattern predicate
Run:
:vimgrep /linux/gj **/*
**/*to search on all files recursivelygflag to search for all occurences in each linejflag to avoid vim to jump automatically on the first occurence
Once the command ran, vim will populate the quickfix list with all the linux
occurences. To see the list, run :copen.
Replace or subsitute all the linux occurences
Here comes vim’s super power, running a command for each line in the quickfix list.
Run:
:cfdo %s/linux/OpenBSD/gc | update
%s/linux/OpenBSDis the subsitute patterngflag replaces all occurences in each linecflag asks to confirm each subsitutionupdateto make sure the file is saved before moving to the next one
For more information on those previous commands, you can try:
:help vimgrep:help cfdo
All of these info are essentially copied from a stackexchange comment.
Thx.