That will be a page for some useful Vim tips which I have searched for once and just want to have them kept somewhere.

Find and replace in multiple files

:args `find . -path '**/node_modules' -prune -false -o -type f -name '*.js'`
:silent! argdo %s/pattern/replacement/gc | update

Explanation:

  • args will store all the files from the find command
  • the -path '**/node_modules' -prune -false -o part is extremely usefull to exclude all the files inside of node_modules directory (can be any directory(s) depending on your project) from search to spead up the processing
  • the silent! will skip any extra messages from output
  • argdo will execute a command for all the files from the arguemnt list
  • update applies changes to all files

Save as root

If you have opened a root owned file for editing while using the non-root user session, this command will help you to save the file as a root user:

:w !sudo tee %

Explanation:

  • ! executes the follow-up command directrly in shell
  • tee is a shell command which redirects the write output of a stream
  • % is a vim specific variable that stores the current filename

So the command will take the output of the file save (:w) and put it to the file which is called same as the file you’re currently editing but as a sudo user.

Perl compatible regular expressions

Just place the \v before the regex and it will do the trick.

/\v(any-templat[e]*)/replace-$1/ge

To be continued…

Will continuously populate it with more tips in future :memo: