Recursively search and replace text in all files in MacOS

How to Recursively Search and Replace Text in All Files on macOS

Steps

find files based on file extension

Use -print0 to terminate strings with null strings, instead of newline characters

This allows proper interpretation of strings with spaces

plays well with xargs -0

xargs and sed to replace with a regex string

Use -0 to look through lists separated by null strings

Use  -i "" to ignore these null strings

Example

find . -name '*.txt' -print0 | xargs -0 sed -i "" "s/form/forms/g"

Use case

While migrating Roam to LogSeq, I had to replace all :: with :, which Roam uses as a shortcut page with different formatting, and which is unsupported on LogSeq.

find . -name '*.md' -print0 | xargs -0 sed -i "" "s/::/:/g"

The above command made it super easy. For more advanced text processing with LogSeq files, check out Extracting information out of logseq where I use gawk to extract specific sections from journals.

Source

https://stackoverflow.com/a/17308739/1782471