How to Replace Text in Files with Ripgrep and Sed

Updated

Learn how to find and replace text in many files with ripgrep (rg) and sed

Ripgrep: How to Replace Text in Files with Ripgrep and Sed

Before we start, make sure you have ripgrep installed on your computer. On a Mac, you can install it with Homebrew:

brew install ripgrep

First, open your terminal and navigate to your project folder. Before you change anything, preview the result with ripgrep's -r flag:

rg 'old_text' -r 'new_text'

The -r flag only changes what ripgrep prints, so your files stay exactly the same. When it looks right, run this to replace the text in every file:

rg -l -0 'old_text' | xargs -0 sed -i '' 's/old_text/new_text/g'

Just replace old_text and new_text with your own text. -l lists only the matching file names, -0 keeps names with spaces safe, and xargs -0 hands them to sed. Don't worry if it prints nothing; that's normal.

On a Mac, the two single quotes after -i matter. If you copy the Linux version, sed -i 's/…/g', you'll get unescaped newline inside substitute pattern and nothing changes. To check the result, run rg 'new_text'.

undefined

If your text contains slashes, like a URL, use | as the delimiter: 's|http://old|https://new|g'. For whole words, swap sed -i '' for perl -pi -e and use \b, because macOS sed doesn't support it.