Find and replace trick

Thursday, April 14, 2022

This is just a short post I wanted to write up in order to document and nice combo of commands that effectively implements a find and replace functionality for an entire codebase, in a single command. The method relies on two tools for doing this, ripgrep and rpl (both available in Debian).

Here's an example of using the command. It assumes that you are trying to replace the string fetch_by_iri with fetchByIri. If you run this command as is it will go ahead and do the replacement of all matches in any files within any subdirectories of your current working directory.

$ rg --files-with-matches fetch_by_iri | xargs rpl fetch_by_iri fetchByIri

Other useful notes:

  1. Passing the -s flag to rpl means "simulation" mode. It's a dry-run where you will just be given some info about what changes would have been made.
  2. Passing the -p flag to rpl means "prompt" mode. It will only make changes you say yes to.