replace snippets

Recursive find and replace on OSX/Linux

Tagged search, replace, sed, osx  Languages bash

Search and replace XXX with YYY in all files:

perl -e "s/XXX/YYY/g;" -pi $(find . -type f)

Troubleshooting

If you get this error:

zsh: argument list too long: perl

Then, your argument list is clearly too long to handle. Use xargs:

find . \
   -type f \
   -exec perl -i -pe's/XXX/YYY/g' {} +

Search and Replace with Sed

Using sed is more complicated, but this should work on at least Linux:

# Find, backup and replace
find . -name "*.rb" -print | xargs sed -i.bak 's/XXX/YYY/g'
# Delete backup files
find . -name '*.bak' -type f -delete

Reference.